Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.
Python agentagentic-aiagentic-frameworkagentic-workflowaiautomationclaudedeepseekgenaigptllmlow-codemcpnextjsno-codeopenaipythonskillsworkflow
feat: workflow new nodes (#4683)
zxhlyh45deaee762e1
diff --git a/web/app/(commonLayout)/datasets/NewDatasetCard.tsx b/web/app/(commonLayout)/datasets/NewDatasetCard.tsxindex 5ce79adadc6..f3e34ff7e22 100644--- a/web/app/(commonLayout)/datasets/NewDatasetCard.tsx+++ b/web/app/(commonLayout)/datasets/NewDatasetCard.tsx@@ -9,7 +9,7 @@ const CreateAppCard = forwardRef<HTMLAnchorElement>((_, ref) => {return (<a ref={ref} className='group flex flex-col col-span-1 bg-gray-200 border-[0.5px] border-black/5 rounded-xl min-h-[160px] transition-all duration-200 ease-in-out cursor-pointer hover:bg-white hover:shadow-lg' href='/datasets/create'>- <div className='shrnik-0 flex items-center p-4 pb-3'>+ <div className='shrink-0 flex items-center p-4 pb-3'><div className='w-10 h-10 flex items-center justify-center border border-gray-200 bg-gray-100 rounded-lg'><Plus className='w-4 h-4 text-gray-500'/></div>diff --git a/web/app/(commonLayout)/tools/custom/page.tsx b/web/app/(commonLayout)/tools/custom/page.tsxdeleted file mode 100644index c666bf347cc..00000000000--- a/web/app/(commonLayout)/tools/custom/page.tsx+++ /dev/null@@ -1,10 +0,0 @@-import React from 'react'--const Custom = () => {- return (- <div>- Custom- </div>- )-}-export default Customdiff --git a/web/app/(commonLayout)/tools/page.tsx b/web/app/(commonLayout)/tools/page.tsxindex 36a76d60d03..066550b3a2a 100644--- a/web/app/(commonLayout)/tools/page.tsx+++ b/web/app/(commonLayout)/tools/page.tsx@@ -2,8 +2,7 @@import type { FC } from 'react'import { useTranslation } from 'react-i18next'import React, { useEffect } from 'react'-import Tools from '@/app/components/tools'-import { LOC } from '@/app/components/tools/types'+import ToolProviderList from '@/app/components/tools/provider-list'const Layout: FC = () => {const { t } = useTranslation()@@ -12,12 +11,6 @@ const Layout: FC = () => {document.title = `${t('tools.title')} - Dify`}, [])- return (- <div className='overflow-hidden' style={{- height: 'calc(100vh - 56px)',- }}>- <Tools loc={LOC.tools} />- </div>- )+ return <ToolProviderList />}export default React.memo(Layout)diff --git a/web/app/(commonLayout)/tools/third-part/page.tsx b/web/app/(commonLayout)/tools/third-part/page.tsxdeleted file mode 100644index d2ae8106093..00000000000--- a/web/app/(commonLayout)/tools/third-part/page.tsx+++ /dev/null@@ -1,10 +0,0 @@-import React from 'react'--const ThirdPart = () => {- return (- <div>- Third part- </div>- )-}-export default ThirdPartdiff --git a/web/app/components/app/app-publisher/index.tsx b/web/app/components/app/app-publisher/index.tsxindex fa7b9ed344d..7e4c584257f 100644--- a/web/app/components/app/app-publisher/index.tsx+++ b/web/app/components/app/app-publisher/index.tsx@@ -23,6 +23,8 @@ import { PlayCircle } from '@/app/components/base/icons/src/vender/line/mediaAndimport { CodeBrowser } from '@/app/components/base/icons/src/vender/line/development'import { LeftIndent02 } from '@/app/components/base/icons/src/vender/line/editor'import { FileText } from '@/app/components/base/icons/src/vender/line/files'+import WorkflowToolConfigureButton from '@/app/components/tools/workflow-tool/configure-button'+import type { InputVar } from '@/app/components/workflow/types'export type AppPublisherProps = {disabled?: boolean@@ -37,6 +39,9 @@ export type AppPublisherProps = {onRestore?: () => Promise<any> | anyonToggle?: (state: boolean) => voidcrossAxisOffset?: number+ toolPublished?: boolean+ inputs?: InputVar[]+ onRefreshData?: () => void}const AppPublisher = ({@@ -50,6 +55,9 @@ const AppPublisher = ({onRestore,onToggle,crossAxisOffset = 0,+ toolPublished,+ inputs,+ onRefreshData,}: AppPublisherProps) => {const { t } = useTranslation()const [published, setPublished] = useState(false)@@ -122,7 +130,7 @@ const AppPublisher = ({</Button></PortalToFollowElemTrigger><PortalToFollowElemContent className='z-[11]'>- <div className='w-[320px] bg-white rounded-2xl border-[0.5px] border-gray-200 shadow-xl'>+ <div className='w-[336px] bg-white rounded-2xl border-[0.5px] border-gray-200 shadow-xl'><div className='p-4 pt-3'><div className='flex items-center h-6 text-xs font-medium text-gray-500 uppercase'>{publishedAt ? t('workflow.common.latestPublished') : t('workflow.common.currentDraftUnpublished')}@@ -202,6 +210,23 @@ const AppPublisher = ({</SuggestedAction>)}<SuggestedAction disabled={!publishedAt} link='./develop' icon={<FileText className='w-4 h-4' />}>{t('workflow.common.accessAPIReference')}</SuggestedAction>+ {appDetail?.mode === 'workflow' && (+ <WorkflowToolConfigureButton+ disabled={!publishedAt}+ published={!!toolPublished}+ detailNeedUpdate={!!toolPublished && published}+ workflowAppId={appDetail?.id}+ icon={{+ content: appDetail?.icon,+ background: appDetail?.icon_background,+ }}+ name={appDetail?.name}+ description={appDetail?.description}+ inputs={inputs}+ handlePublish={handlePublish}+ onRefreshData={onRefreshData}+ />+ )}</div></div></PortalToFollowElemContent>diff --git a/web/app/components/app/configuration/config/agent/agent-tools/choose-tool/index.tsx b/web/app/components/app/configuration/config/agent/agent-tools/choose-tool/index.tsxdeleted file mode 100644index d47406e95b7..00000000000--- a/web/app/components/app/configuration/config/agent/agent-tools/choose-tool/index.tsx+++ /dev/null@@ -1,77 +0,0 @@-'use client'-import type { FC } from 'react'-import React from 'react'-import { useContext } from 'use-context-selector'-import { useTranslation } from 'react-i18next'-import produce from 'immer'-import Tools from '@/app/components/tools'-import { LOC } from '@/app/components/tools/types'-import Drawer from '@/app/components/base/drawer-plus'-import ConfigContext from '@/context/debug-configuration'-import type { ModelConfig } from '@/models/debug'-import I18n from '@/context/i18n'--type Props = {- show: boolean- onHide: () => void- selectedProviderId?: string-}--const ChooseTool: FC<Props> = ({- show,- onHide,- selectedProviderId,-}) => {- const { t } = useTranslation()- const { locale } = useContext(I18n)- const {- modelConfig,- setModelConfig,- } = useContext(ConfigContext)- if (!show)- return null-- return (- <Drawer- isShow- onHide={onHide}- title={t('tools.addTool') as string}- panelClassName='mt-2 !w-[760px]'- maxWidthClassName='!max-w-[760px]'- height='calc(100vh - 16px)'- contentClassName='!bg-gray-100'- headerClassName='!border-b-black/5'- body={- <Tools- loc={LOC.app}- selectedProviderId={selectedProviderId}- onAddTool={(collection, tool) => {- const parameters: Record<string, string> = {}- if (tool.parameters) {- tool.parameters.forEach((item) => {- parameters[item.name] = ''- })- }-- const nexModelConfig = produce(modelConfig, (draft: ModelConfig) => {- draft.agentConfig.tools.push({- provider_id: collection.id || collection.name,- provider_type: collection.type,- provider_name: collection.name,- tool_name: tool.name,- tool_label: tool.label[locale] || tool.label[locale.replaceAll('-', '_')],- tool_parameters: parameters,- enabled: true,- })- })- setModelConfig(nexModelConfig)- }}- addedTools={(modelConfig?.agentConfig?.tools as any) || []}- />- }- isShowMask={true}- clickOutsideNotOpen={false}- />- )-}-export default React.memo(ChooseTool)diff --git a/web/app/components/app/configuration/config/agent/agent-tools/index.tsx b/web/app/components/app/configuration/config/agent/agent-tools/index.tsxindex b92ff949833..c59145aa9d1 100644--- a/web/app/components/app/configuration/config/agent/agent-tools/index.tsx+++ b/web/app/components/app/configuration/config/agent/agent-tools/index.tsx@@ -6,7 +6,6 @@ import cn from 'classnames'import { useContext } from 'use-context-selector'import produce from 'immer'import { useFormattingChangedDispatcher } from '../../../debug/hooks'-import ChooseTool from './choose-tool'import SettingBuiltInTool from './setting-built-in-tool'import Panel from '@/app/components/app/configuration/base/feature-panel'import Tooltip from '@/app/components/base/tooltip'@@ -22,6 +21,7 @@ import { MAX_TOOLS_NUM } from '@/config'import { AlertTriangle } from '@/app/components/base/icons/src/vender/solid/alertsAndFeedback'import TooltipPlus from '@/app/components/base/tooltip-plus'import { DefaultToolIcon } from '@/app/components/base/icons/src/public/other'+import AddToolModal from '@/app/components/tools/add-tool-modal'type AgentToolWithMoreInfo = AgentTool & { icon: any; collection?: Collection } | nullconst AgentTools: FC = () => {@@ -31,7 +31,6 @@ const AgentTools: FC = () => {const formattingChangedDispatcher = useFormattingChangedDispatcher()const [currentTool, setCurrentTool] = useState<AgentToolWithMoreInfo>(null)- const [selectedProviderId, setSelectedProviderId] = useState<string | undefined>(undefined)const [isShowSettingTool, setIsShowSettingTool] = useState(false)const tools = (modelConfig?.agentConfig?.tools as AgentTool[] || []).map((item) => {const collection = collectionList.find(collection => collection.id === item.provider_id && collection.type === item.provider_type)@@ -78,10 +77,7 @@ const AgentTools: FC = () => {{tools.length < MAX_TOOLS_NUM && (<><div className='ml-3 mr-1 h-3.5 w-px bg-gray-200'></div>- <OperationBtn type="add" onClick={() => {- setSelectedProviderId(undefined)- setIsShowChooseTool(true)- }} />+ <OperationBtn type="add" onClick={() => setIsShowChooseTool(true)} /></>)}</div>@@ -116,10 +112,14 @@ const AgentTools: FC = () => {/>))}<div- title={item.tool_name}className={cn((item.isDeleted || item.notAuthor) ? 'line-through opacity-50' : '', 'grow w-0 ml-2 leading-[18px] text-[13px] font-medium text-gray-800 truncate')}>- {item.tool_label || item.tool_name}+ <span className='text-gray-800 pr-2'>{item.provider_type === CollectionType.builtIn ? item.provider_name : item.tool_label}</span>+ <TooltipPlus+ popupContent={t('tools.toolNameUsageTip')}+ >+ <span className='text-gray-500'>{item.tool_name}</span>+ </TooltipPlus></div></div><div className='shrink-0 ml-1 flex items-center'>@@ -130,10 +130,8 @@ const AgentTools: FC = () => {popupContent={t(`tools.${item.isDeleted ? 'toolRemoved' : 'notAuthorized'}`)}><div className='mr-1 p-1 rounded-md hover:bg-black/5 cursor-pointer' onClick={() => {- if (item.notAuthor) {- setSelectedProviderId(item.provider_id)+ if (item.notAuthor)setIsShowChooseTool(true)- }}}><AlertTriangle className='w-4 h-4 text-[#F79009]' /></div>@@ -153,7 +151,6 @@ const AgentTools: FC = () => {): (<div className='hidden group-hover:flex items-center'>- {/* {item.provider_type === CollectionType.builtIn && ( */}<TooltipPluspopupContent={t('tools.setBuiltInTools.infoAndSetting')}>@@ -164,7 +161,6 @@ const AgentTools: FC = () => {<InfoCircle className='w-4 h-4 text-gray-500' /></div></TooltipPlus>- {/* )} */}<div className='p-1 rounded-md hover:bg-black/5 cursor-pointer' onClick={() => {const newModelConfig = produce(modelConfig, (draft) => {@@ -197,11 +193,7 @@ const AgentTools: FC = () => {</div ></Panel >{isShowChooseTool && (- <ChooseTool- show- onHide={() => setIsShowChooseTool(false)}- selectedProviderId={selectedProviderId}- />+ <AddToolModal onHide={() => setIsShowChooseTool(false)} />)}{isShowSettingTool && (diff --git a/web/app/components/app/configuration/config/agent/agent-tools/setting-built-in-tool.tsx b/web/app/components/app/configuration/config/agent/agent-tools/setting-built-in-tool.tsxindex 9eb2657fcf5..b35217732fc 100644--- a/web/app/components/app/configuration/config/agent/agent-tools/setting-built-in-tool.tsx+++ b/web/app/components/app/configuration/config/agent/agent-tools/setting-built-in-tool.tsx@@ -8,7 +8,8 @@ import Drawer from '@/app/components/base/drawer-plus'import Form from '@/app/components/header/account-setting/model-provider-page/model-modal/Form'import { addDefaultValue, toolParametersToFormSchemas } from '@/app/components/tools/utils/to-form-schema'import type { Collection, Tool } from '@/app/components/tools/types'-import { fetchBuiltInToolList, fetchCustomToolList, fetchModelToolList } from '@/service/tools'+import { CollectionType } from '@/app/components/tools/types'+import { fetchBuiltInToolList, fetchCustomToolList, fetchModelToolList, fetchWorkflowToolList } from '@/service/tools'import I18n from '@/context/i18n'import Button from '@/app/components/base/button'import Loading from '@/app/components/base/loading'@@ -64,6 +65,8 @@ const SettingBuiltInTool: FC<Props> = ({resolve(await fetchModelToolList(collection.name))else if (isBuiltIn)resolve(await fetchBuiltInToolList(collection.name))+ else if (collection.type === CollectionType.workflow)+ resolve(await fetchWorkflowToolList(collection.id))elseresolve(await fetchCustomToolList(collection.name))}())@@ -78,7 +81,7 @@ const SettingBuiltInTool: FC<Props> = ({catch (e) { }setIsLoading(false)})()- }, [collection?.name])+ }, [collection?.name, collection?.id, collection?.type])useEffect(() => {setCurrType((!readonly && hasSetting) ? 'setting' : 'info')@@ -150,7 +153,7 @@ const SettingBuiltInTool: FC<Props> = ({onHide={onHide}title={(<div className='flex'>- {collection.icon === 'string'+ {typeof collection.icon === 'string'? (<divclassName='w-6 h-6 bg-cover bg-center rounded-md'@@ -189,8 +192,8 @@ const SettingBuiltInTool: FC<Props> = ({</>)}</div>)}- panelClassName='mt-[65px] !w-[480px]'- maxWidthClassName='!max-w-[480px]'+ panelClassName='mt-[65px] !w-[405px]'+ maxWidthClassName='!max-w-[405px]'height='calc(100vh - 65px)'headerClassName='!border-b-black/5'body={@@ -212,7 +215,7 @@ const SettingBuiltInTool: FC<Props> = ({</div>)}</div>}- isShowMask={true}+ isShowMask={false}clickOutsideNotOpen={false}/>)diff --git a/web/app/components/app/log/list.tsx b/web/app/components/app/log/list.tsxindex 3c420d342f1..c2ce0b56330 100644--- a/web/app/components/app/log/list.tsx+++ b/web/app/components/app/log/list.tsx@@ -164,7 +164,7 @@ function DetailPanel<T extends ChatConversationFullDetailResponse | CompletionCoconst { userProfile: { timezone } } = useAppContext()const { formatTime } = useTimestamp()const { onClose, appDetail } = useContext(DrawerContext)- const { currentLogItem, setCurrentLogItem, showPromptLogModal, setShowPromptLogModal, showAgentLogModal, setShowAgentLogModal, showMessageLogModal, setShowMessageLogModal } = useAppStore(useShallow(state => ({+ const { currentLogItem, setCurrentLogItem, showPromptLogModal, setShowPromptLogModal, showAgentLogModal, setShowAgentLogModal, showMessageLogModal, setShowMessageLogModal, currentLogModalActiveTab } = useAppStore(useShallow(state => ({currentLogItem: state.currentLogItem,setCurrentLogItem: state.setCurrentLogItem,showPromptLogModal: state.showPromptLogModal,@@ -173,6 +173,7 @@ function DetailPanel<T extends ChatConversationFullDetailResponse | CompletionCosetShowAgentLogModal: state.setShowAgentLogModal,showMessageLogModal: state.showMessageLogModal,setShowMessageLogModal: state.setShowMessageLogModal,+ currentLogModalActiveTab: state.currentLogModalActiveTab,})))const { t } = useTranslation()const [items, setItems] = React.useState<IChatItem[]>([])@@ -444,6 +445,7 @@ function DetailPanel<T extends ChatConversationFullDetailResponse | CompletionCosetCurrentLogItem()setShowMessageLogModal(false)}}+ defaultTab={currentLogModalActiveTab}/>)}</div>diff --git a/web/app/components/app/store.ts b/web/app/components/app/store.tsindex aaa42d71103..eb7ad62f779 100644--- a/web/app/components/app/store.ts+++ b/web/app/components/app/store.ts@@ -6,6 +6,7 @@ type State = {appDetail?: AppappSidebarExpand: stringcurrentLogItem?: IChatItem+ currentLogModalActiveTab: stringshowPromptLogModal: booleanshowAgentLogModal: booleanshowMessageLogModal: boolean@@ -15,6 +16,7 @@ type Action = {setAppDetail: (appDetail?: App) => voidsetAppSiderbarExpand: (state: string) => voidsetCurrentLogItem: (item?: IChatItem) => void+ setCurrentLogModalActiveTab: (tab: string) => voidsetShowPromptLogModal: (showPromptLogModal: boolean) => voidsetShowAgentLogModal: (showAgentLogModal: boolean) => voidsetShowMessageLogModal: (showMessageLogModal: boolean) => void@@ -26,11 +28,23 @@ export const useStore = create<State & Action>(set => ({appSidebarExpand: '',setAppSiderbarExpand: appSidebarExpand => set(() => ({ appSidebarExpand })),currentLogItem: undefined,+ currentLogModalActiveTab: 'DETAIL',setCurrentLogItem: currentLogItem => set(() => ({ currentLogItem })),+ setCurrentLogModalActiveTab: currentLogModalActiveTab => set(() => ({ currentLogModalActiveTab })),showPromptLogModal: false,setShowPromptLogModal: showPromptLogModal => set(() => ({ showPromptLogModal })),showAgentLogModal: false,setShowAgentLogModal: showAgentLogModal => set(() => ({ showAgentLogModal })),showMessageLogModal: false,- setShowMessageLogModal: showMessageLogModal => set(() => ({ showMessageLogModal })),+ setShowMessageLogModal: showMessageLogModal => set(() => {+ if (showMessageLogModal) {+ return { showMessageLogModal }+ }+ else {+ return {+ showMessageLogModal,+ currentLogModalActiveTab: 'DETAIL',+ }+ }+ }),}))diff --git a/web/app/components/base/chat/chat/answer/index.tsx b/web/app/components/base/chat/chat/answer/index.tsxindex f2739f6374c..4e88283663a 100644--- a/web/app/components/base/chat/chat/answer/index.tsx+++ b/web/app/components/base/chat/chat/answer/index.tsx@@ -97,7 +97,7 @@ const Answer: FC<AnswerProps> = ({)}</div>- <div className='chat-answer-container grow w-0 ml-4' ref={containerRef}>+ <div className='chat-answer-container group grow w-0 ml-4' ref={containerRef}><div className={`group relative pr-10 ${chatAnswerContainerInner}`}><AnswerTriangle className='absolute -left-2 top-0 w-2 h-3 text-gray-100' /><div@@ -131,7 +131,12 @@ const Answer: FC<AnswerProps> = ({}{workflowProcess && (- <WorkflowProcess data={workflowProcess} hideInfo hideProcessDetail={hideProcessDetail} />+ <WorkflowProcess+ data={workflowProcess}+ item={item}+ hideInfo+ hideProcessDetail={hideProcessDetail}+ />)}{diff --git a/web/app/components/base/chat/chat/answer/workflow-process.tsx b/web/app/components/base/chat/chat/answer/workflow-process.tsxindex 4eef0b938fb..d47db40437d 100644--- a/web/app/components/base/chat/chat/answer/workflow-process.tsx+++ b/web/app/components/base/chat/chat/answer/workflow-process.tsx@@ -1,20 +1,23 @@import {+ useCallback,useEffect,useMemo,useState,} from 'react'import cn from 'classnames'import { useTranslation } from 'react-i18next'-import type { WorkflowProcess } from '../../types'+import type { ChatItem, WorkflowProcess } from '../../types'import { CheckCircle } from '@/app/components/base/icons/src/vender/solid/general'import { AlertCircle } from '@/app/components/base/icons/src/vender/solid/alertsAndFeedback'import { Loading02 } from '@/app/components/base/icons/src/vender/line/general'import { ChevronRight } from '@/app/components/base/icons/src/vender/line/arrows'import { WorkflowRunningStatus } from '@/app/components/workflow/types'import NodePanel from '@/app/components/workflow/run/node'+import { useStore as useAppStore } from '@/app/components/app/store'type WorkflowProcessProps = {data: WorkflowProcess+ item?: ChatItemgrayBg?: booleanexpand?: booleanhideInfo?: boolean@@ -22,6 +25,7 @@ type WorkflowProcessProps = {}const WorkflowProcessItem = ({data,+ item,grayBg,expand = false,hideInfo = false,@@ -48,6 +52,16 @@ const WorkflowProcessItem = ({setCollapse(!expand)}, [expand])+ const setCurrentLogItem = useAppStore(s => s.setCurrentLogItem)+ const setShowMessageLogModal = useAppStore(s => s.setShowMessageLogModal)+ const setCurrentLogModalActiveTab = useAppStore(s => s.setCurrentLogModalActiveTab)++ const showIterationDetail = useCallback(() => {+ setCurrentLogItem(item)+ setCurrentLogModalActiveTab('TRACING')+ setShowMessageLogModal(true)+ }, [item, setCurrentLogItem, setCurrentLogModalActiveTab, setShowMessageLogModal])+return (<divclassName={cn(@@ -97,6 +111,7 @@ const WorkflowProcessItem = ({nodeInfo={node}hideInfo={hideInfo}hideProcessDetail={hideProcessDetail}+ onShowIterationDetail={showIterationDetail}/></div>))diff --git a/web/app/components/base/chat/chat/hooks.ts b/web/app/components/base/chat/chat/hooks.tsindex 382c01e167b..be1269858ee 100644--- a/web/app/components/base/chat/chat/hooks.ts+++ b/web/app/components/base/chat/chat/hooks.ts@@ -237,6 +237,8 @@ export const useChat = (isAnswer: true,}+ let isInIteration = false+handleResponding(true)hasStopResponded.current = false@@ -467,7 +469,41 @@ export const useChat = (}}))},+ onIterationStart: ({ data }) => {+ responseItem.workflowProcess!.tracing!.push({+ ...data,+ status: WorkflowRunningStatus.Running,+ } as any)+ handleUpdateChatList(produce(chatListRef.current, (draft) => {+ const currentIndex = draft.findIndex(item => item.id === responseItem.id)+ draft[currentIndex] = {+ ...draft[currentIndex],+ ...responseItem,+ }+ }))+ isInIteration = true+ },+ onIterationFinish: ({ data }) => {+ const tracing = responseItem.workflowProcess!.tracing!+ tracing[tracing.length - 1] = {+ ...tracing[tracing.length - 1],+ ...data,+ status: WorkflowRunningStatus.Succeeded,+ } as any++ handleUpdateChatList(produce(chatListRef.current, (draft) => {+ const currentIndex = draft.findIndex(item => item.id === responseItem.id)+ draft[currentIndex] = {+ ...draft[currentIndex],+ ...responseItem,+ }+ }))+ isInIteration = false+ },onNodeStarted: ({ data }) => {+ if (isInIteration)+ return+responseItem.workflowProcess!.tracing!.push({...data,status: WorkflowRunningStatus.Running,@@ -481,6 +517,9 @@ export const useChat = (}))},onNodeFinished: ({ data }) => {+ if (isInIteration)+ return+const currentIndex = responseItem.workflowProcess!.tracing!.findIndex(item => item.node_id === data.node_id)responseItem.workflowProcess!.tracing[currentIndex] = data as anyhandleUpdateChatList(produce(chatListRef.current, (draft) => {diff --git a/web/app/components/base/drawer-plus/index.tsx b/web/app/components/base/drawer-plus/index.tsxindex 3415b067aa8..3eabe1973e1 100644--- a/web/app/components/base/drawer-plus/index.tsx+++ b/web/app/components/base/drawer-plus/index.tsx@@ -20,6 +20,7 @@ type Props = {foot?: JSX.ElementisShowMask?: booleanclickOutsideNotOpen?: boolean+ positionCenter?: boolean}const DrawerPlus: FC<Props> = ({@@ -36,6 +37,7 @@ const DrawerPlus: FC<Props> = ({foot,isShowMask,clickOutsideNotOpen = true,+ positionCenter,}) => {const ref = useRef(null)const media = useBreakpoints()@@ -46,7 +48,15 @@ const DrawerPlus: FC<Props> = ({return (// clickOutsideNotOpen to fix confirm modal click cause drawer close- <Drawer isOpen={isShow} clickOutsideNotOpen={clickOutsideNotOpen} onClose={onHide} footer={null} mask={isMobile || isShowMask} panelClassname={`mt-16 mx-2 sm:mr-2 mb-3 !p-0 ${panelClassName} ${maxWidthClassName} rounded-xl`}>+ <Drawer+ isOpen={isShow}+ clickOutsideNotOpen={clickOutsideNotOpen}+ onClose={onHide}+ footer={null}+ mask={isMobile || isShowMask}+ positionCenter={positionCenter}+ panelClassname={cn('mt-16 mx-2 sm:mr-2 mb-3 !p-0 rounded-xl', panelClassName, maxWidthClassName)}+ ><divclassName={cn(contentClassName, 'w-full flex flex-col bg-white border-[0.5px] border-gray-200 rounded-xl shadow-xl')}style={{diff --git a/web/app/components/base/drawer/index.tsx b/web/app/components/base/drawer/index.tsxindex 911a785fe1e..467c8253b93 100644--- a/web/app/components/base/drawer/index.tsx+++ b/web/app/components/base/drawer/index.tsx@@ -1,4 +1,5 @@'use client'+import cn from 'classnames'import { Dialog } from '@headlessui/react'import { useTranslation } from 'react-i18next'import { XMarkIcon } from '@heroicons/react/24/outline'@@ -11,6 +12,7 @@ export type IDrawerProps = {children: React.ReactNodefooter?: React.ReactNodemask?: boolean+ positionCenter?: booleanisOpen: boolean// closable: booleanshowClose?: boolean@@ -27,6 +29,7 @@ export default function Drawer({children,footer,mask = true,+ positionCenter,showClose = false,isOpen,clickOutsideNotOpen,@@ -42,14 +45,12 @@ export default function Drawer({onClose={() => !clickOutsideNotOpen && onClose()}className="fixed z-30 inset-0 overflow-y-auto">- <div className="flex w-screen h-screen justify-end">+ <div className={cn('flex w-screen h-screen justify-end', positionCenter && '!justify-center')}>{/* mask */}<Dialog.Overlay- className={`z-40 fixed inset-0 ${!mask ? '' : 'bg-black bg-opacity-30'}`}+ className={cn('z-40 fixed inset-0', mask && 'bg-black bg-opacity-30')}/>- <div className={`relative z-50 flex flex-col justify-between bg-white w-full- max-w-sm p-6 overflow-hidden text-left align-middle- shadow-xl ${panelClassname}`}>+ <div className={cn('relative z-50 flex flex-col justify-between bg-white w-full max-w-sm p-6 overflow-hidden text-left align-middle shadow-xl', panelClassname)}><>{title && <Dialog.Titleas="h3"diff --git a/web/app/components/base/icons/assets/public/common/d.svg b/web/app/components/base/icons/assets/public/common/d.svgnew file mode 100644index 00000000000..fdcd607dfce--- /dev/null+++ b/web/app/components/base/icons/assets/public/common/d.svg@@ -0,0 +1,16 @@+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">+<path d="M2 1H7.94339C11.8094 1 14.9434 4.13401 14.9434 8C14.9434 11.866 11.8094 15 7.9434 15H2V1Z" fill="white"/>+<path d="M2 1H7.94339C11.8094 1 14.9434 4.13401 14.9434 8C14.9434 11.866 11.8094 15 7.9434 15H2V1Z" fill="url(#paint0_angular_19344_240446)"/>+<path d="M7.94336 8H8.20751V15H7.94336V8Z" fill="url(#paint1_linear_19344_240446)"/>+<defs>+<radialGradient id="paint0_angular_19344_240446" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(7.9434 8) rotate(90) scale(8.75 8.75)">+<stop stop-color="#001FC2"/>+<stop offset="0.711334" stop-color="#0667F8" stop-opacity="0.2"/>+<stop offset="1" stop-color="#155EEF" stop-opacity="0"/>+</radialGradient>+<linearGradient id="paint1_linear_19344_240446" x1="8.06244" y1="8.43754" x2="7.93744" y2="9.20317" gradientUnits="userSpaceOnUse">+<stop stop-color="white" stop-opacity="0"/>+<stop offset="1" stop-color="white"/>+</linearGradient>+</defs>+</svg>diff --git a/web/app/components/base/icons/assets/vender/line/files/folder.svg b/web/app/components/base/icons/assets/vender/line/files/folder.svgnew file mode 100644index 00000000000..248708bd3d7--- /dev/null+++ b/web/app/components/base/icons/assets/vender/line/files/folder.svg@@ -0,0 +1,5 @@+<svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">+<g id="folder">+<path id="Icon" d="M12.8327 11.0833C12.8327 11.3928 12.7098 11.6895 12.491 11.9083C12.2722 12.1271 11.9754 12.25 11.666 12.25H2.33268C2.02326 12.25 1.72652 12.1271 1.50772 11.9083C1.28893 11.6895 1.16602 11.3928 1.16602 11.0833V2.91667C1.16602 2.60725 1.28893 2.3105 1.50772 2.09171C1.72652 1.87292 2.02326 1.75 2.33268 1.75H5.24935L6.41602 3.5H11.666C11.9754 3.5 12.2722 3.62292 12.491 3.84171C12.7098 4.0605 12.8327 4.35725 12.8327 4.66667V11.0833Z" stroke="#344054" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>+</g>+</svg>diff --git a/web/app/components/base/icons/assets/vender/line/others/apps-02.svg b/web/app/components/base/icons/assets/vender/line/others/apps-02.svgnew file mode 100644index 00000000000..8e1fec9ecc9--- /dev/null+++ b/web/app/components/base/icons/assets/vender/line/others/apps-02.svg@@ -0,0 +1,5 @@+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">+<g id="apps-2-line">+<path id="Vector" d="M4.66602 7.6665C3.00916 7.6665 1.66602 6.32336 1.66602 4.6665C1.66602 3.00965 3.00916 1.6665 4.66602 1.6665C6.32287 1.6665 7.66602 3.00965 7.66602 4.6665C7.66602 6.32336 6.32287 7.6665 4.66602 7.6665ZM4.66602 14.3332C3.00916 14.3332 1.66602 12.99 1.66602 11.3332C1.66602 9.6763 3.00916 8.33317 4.66602 8.33317C6.32287 8.33317 7.66602 9.6763 7.66602 11.3332C7.66602 12.99 6.32287 14.3332 4.66602 14.3332ZM11.3327 7.6665C9.67582 7.6665 8.33268 6.32336 8.33268 4.6665C8.33268 3.00965 9.67582 1.6665 11.3327 1.6665C12.9895 1.6665 14.3327 3.00965 14.3327 4.6665C14.3327 6.32336 12.9895 7.6665 11.3327 7.6665ZM11.3327 14.3332C9.67582 14.3332 8.33268 12.99 8.33268 11.3332C8.33268 9.6763 9.67582 8.33317 11.3327 8.33317C12.9895 8.33317 14.3327 9.6763 14.3327 11.3332C14.3327 12.99 12.9895 14.3332 11.3327 14.3332ZM4.66602 6.33317C5.58649 6.33317 6.33268 5.58698 6.33268 4.6665C6.33268 3.74603 5.58649 2.99984 4.66602 2.99984C3.74554 2.99984 2.99935 3.74603 2.99935 4.6665C2.99935 5.58698 3.74554 6.33317 4.66602 6.33317ZM4.66602 12.9998C5.58649 12.9998 6.33268 12.2536 6.33268 11.3332C6.33268 10.4127 5.58649 9.6665 4.66602 9.6665C3.74554 9.6665 2.99935 10.4127 2.99935 11.3332C2.99935 12.2536 3.74554 12.9998 4.66602 12.9998ZM11.3327 6.33317C12.2531 6.33317 12.9993 5.58698 12.9993 4.6665C12.9993 3.74603 12.2531 2.99984 11.3327 2.99984C10.4122 2.99984 9.66602 3.74603 9.66602 4.6665C9.66602 5.58698 10.4122 6.33317 11.3327 6.33317ZM11.3327 12.9998C12.2531 12.9998 12.9993 12.2536 12.9993 11.3332C12.9993 10.4127 12.2531 9.6665 11.3327 9.6665C10.4122 9.6665 9.66602 10.4127 9.66602 11.3332C9.66602 12.2536 10.4122 12.9998 11.3327 12.9998Z" fill="#155EEF"/>+</g>+</svg>diff --git a/web/app/components/base/icons/assets/vender/line/others/colors.svg b/web/app/components/base/icons/assets/vender/line/others/colors.svgnew file mode 100644index 00000000000..3173ef4baed--- /dev/null+++ b/web/app/components/base/icons/assets/vender/line/others/colors.svg@@ -0,0 +1,10 @@+<svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">+<g id="colors" clip-path="url(#clip0_18499_53582)">+<path id="Icon" d="M7.00032 11.9422C7.61954 12.4964 8.43724 12.8334 9.33366 12.8334C11.2667 12.8334 12.8337 11.2664 12.8337 9.33342C12.8337 7.71938 11.7411 6.36051 10.2552 5.95602M3.74543 5.95601C2.25954 6.3605 1.16699 7.71937 1.16699 9.33341C1.16699 11.2664 2.734 12.8334 4.66699 12.8334C6.59999 12.8334 8.16699 11.2664 8.16699 9.33341C8.16699 8.87813 8.08006 8.44314 7.92189 8.04415M10.5003 4.66675C10.5003 6.59974 8.93332 8.16675 7.00033 8.16675C5.06733 8.16675 3.50033 6.59974 3.50033 4.66675C3.50033 2.73375 5.06733 1.16675 7.00033 1.16675C8.93332 1.16675 10.5003 2.73375 10.5003 4.66675Z" stroke="#344054" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round"/>+</g>+<defs>+<clipPath id="clip0_18499_53582">+<rect width="14" height="14" fill="white"/>+</clipPath>+</defs>+</svg>diff --git a/web/app/components/base/icons/assets/vender/line/others/exchange-02.svg b/web/app/components/base/icons/assets/vender/line/others/exchange-02.svgnew file mode 100644index 00000000000..45d2770277f--- /dev/null+++ b/web/app/components/base/icons/assets/vender/line/others/exchange-02.svg@@ -0,0 +1,3 @@+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">+<path d="M4.66602 14.3334C3.00916 14.3334 1.66602 12.9903 1.66602 11.3334C1.66602 9.67655 3.00916 8.33342 4.66602 8.33342C6.32287 8.33342 7.66602 9.67655 7.66602 11.3334C7.66602 12.9903 6.32287 14.3334 4.66602 14.3334ZM11.3327 7.66675C9.67582 7.66675 8.33268 6.3236 8.33268 4.66675C8.33268 3.00989 9.67582 1.66675 11.3327 1.66675C12.9895 1.66675 14.3327 3.00989 14.3327 4.66675C14.3327 6.3236 12.9895 7.66675 11.3327 7.66675ZM4.66602 13.0001C5.58649 13.0001 6.33268 12.2539 6.33268 11.3334C6.33268 10.4129 5.58649 9.66675 4.66602 9.66675C3.74554 9.66675 2.99935 10.4129 2.99935 11.3334C2.99935 12.2539 3.74554 13.0001 4.66602 13.0001ZM11.3327 6.33342C12.2531 6.33342 12.9993 5.58722 12.9993 4.66675C12.9993 3.74627 12.2531 3.00008 11.3327 3.00008C10.4122 3.00008 9.66602 3.74627 9.66602 4.66675C9.66602 5.58722 10.4122 6.33342 11.3327 6.33342ZM1.99935 5.33341C1.99935 3.49247 3.49174 2.00008 5.33268 2.00008H7.33268V3.33341H5.33268C4.22812 3.33341 3.33268 4.22885 3.33268 5.33341V7.33342H1.99935V5.33341ZM13.9993 8.66675H12.666V10.6667C12.666 11.7713 11.7706 12.6667 10.666 12.6667H8.66602V14.0001H10.666C12.5069 14.0001 13.9993 12.5077 13.9993 10.6667V8.66675Z" fill="#344054"/>+</svg>diff --git a/web/app/components/base/icons/assets/vender/line/others/file-code.svg b/web/app/components/base/icons/assets/vender/line/others/file-code.svgnew file mode 100644index 00000000000..eb77033a0a4--- /dev/null+++ b/web/app/components/base/icons/assets/vender/line/others/file-code.svg@@ -0,0 +1,3 @@+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">+<path d="M10 2.66659H3.33333V13.3333H12.6667V5.33325H10V2.66659ZM2 1.99445C2 1.62929 2.29833 1.33325 2.66567 1.33325H10.6667L13.9998 4.66658L14 13.9949C14 14.3659 13.7034 14.6666 13.3377 14.6666H2.66227C2.29651 14.6666 2 14.3631 2 14.0054V1.99445ZM11.7713 7.99992L9.4142 10.3569L8.4714 9.41412L9.8856 7.99992L8.4714 6.58571L9.4142 5.6429L11.7713 7.99992ZM4.22877 7.99992L6.58579 5.6429L7.5286 6.58571L6.11438 7.99992L7.5286 9.41412L6.58579 10.3569L4.22877 7.99992Z" fill="#344054"/>+</svg>diff --git a/web/app/components/base/icons/assets/vender/line/others/tools.svg b/web/app/components/base/icons/assets/vender/line/others/tools.svgnew file mode 100644index 00000000000..a10f5391b18--- /dev/null+++ b/web/app/components/base/icons/assets/vender/line/others/tools.svg@@ -0,0 +1,14 @@+<svg width="16" height="17" viewBox="0 0 16 17" fill="none" xmlns="http://www.w3.org/2000/svg">+<g id="Tools" clip-path="url(#clip0_5381_39479)">+<path id="vector" d="M13.4375 14.4375V6.8125H2.5625V14.4375C2.5625 14.9898 3.01022 15.4375 3.5625 15.4375H12.4375C12.9898 15.4375 13.4375 14.9898 13.4375 14.4375Z" stroke="#344054" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round"/>+<path id="vector_2" d="M13.6254 2.875L11.1738 6.47327" stroke="#344054" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round"/>+<path id="vector_3" d="M6.3125 9.8125H9.6875" stroke="#344054" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round"/>+<path id="vector_4" d="M8.63355 1.88044L8.75 1.64754L8.86645 1.88044C8.97531 2.09816 9.15184 2.27469 9.36956 2.38355L9.60246 2.5L9.36956 2.61645C9.15184 2.72531 8.97531 2.90184 8.86645 3.11956L8.75 3.35246L8.63355 3.11956C8.52469 2.90184 8.34816 2.72531 8.13044 2.61645L7.89754 2.5L8.13044 2.38355C8.34816 2.27469 8.52469 2.09816 8.63355 1.88044Z" stroke="#344054" stroke-width="1.25" stroke-linecap="square" stroke-linejoin="round"/>+<path id="vector_5" d="M4.625 3.14754L4.61865 3.16025C4.51946 3.35862 4.35862 3.51946 4.16025 3.61865L4.14754 3.625L4.16025 3.63135C4.35862 3.73054 4.51946 3.89138 4.61865 4.08975L4.625 4.10246L4.63135 4.08975C4.73054 3.89138 4.89138 3.73054 5.08975 3.63135L5.10246 3.625L5.08975 3.61865C4.89138 3.51946 4.73054 3.35862 4.63135 3.16025L4.625 3.14754ZM4.625 3.14754L4.63135 3.16025L4.625 3.14754Z" stroke="#344054" stroke-width="1.25" stroke-linecap="square" stroke-linejoin="round"/>+</g>+<defs>+<clipPath id="clip0_5381_39479">+<rect width="16" height="16" fill="white" transform="translate(0 0.5)"/>+</clipPath>+</defs>+</svg>diff --git a/web/app/components/base/icons/assets/vender/workflow/iteration-start.svg b/web/app/components/base/icons/assets/vender/workflow/iteration-start.svgnew file mode 100644index 00000000000..a1cc7635965--- /dev/null+++ b/web/app/components/base/icons/assets/vender/workflow/iteration-start.svg@@ -0,0 +1,5 @@+<svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">+<g id="icons/block-start">+<path id="Vector" d="M6.8498 1.72732C6.3379 1.3754 5.6621 1.3754 5.1502 1.72732L2.1502 3.78982C1.74317 4.06965 1.5 4.53193 1.5 5.02588V8.99983C1.5 9.82828 2.17158 10.4998 3 10.4998H4.25C4.52614 10.4998 4.75 10.276 4.75 9.99983V8.24983C4.75 7.55948 5.30965 6.99983 6 6.99983C6.69035 6.99983 7.25 7.55948 7.25 8.24983V9.99983C7.25 10.276 7.47385 10.4998 7.75 10.4998H9C9.82845 10.4998 10.5 9.82828 10.5 8.99983V5.02588C10.5 4.53193 10.2568 4.06965 9.8498 3.78982L6.8498 1.72732Z" fill="white"/>+</g>+</svg>diff --git a/web/app/components/base/icons/assets/vender/workflow/iteration.svg b/web/app/components/base/icons/assets/vender/workflow/iteration.svgnew file mode 100644index 00000000000..2a74faca69b--- /dev/null+++ b/web/app/components/base/icons/assets/vender/workflow/iteration.svg@@ -0,0 +1,5 @@+<svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">+<g id="icons/iteration">+<path id="Vector" d="M6.82849 0.754349C6.6007 0.526545 6.23133 0.526545 6.00354 0.754349C5.77573 0.982158 5.77573 1.3515 6.00354 1.57931L6.82849 0.754349ZM8.16602 2.91683L8.57849 3.32931C8.80628 3.1015 8.80628 2.73216 8.57849 2.50435L8.16602 2.91683ZM6.00354 4.25435C5.77573 4.48216 5.77573 4.8515 6.00354 5.07931C6.23133 5.30711 6.6007 5.30711 6.82849 5.07931L6.00354 4.25435ZM7.99516 9.74597C8.22295 9.51818 8.22295 9.14881 7.99516 8.92102C7.76737 8.69323 7.398 8.69323 7.17021 8.92102L7.99516 9.74597ZM5.83268 11.0835L5.4202 10.671C5.1924 10.8988 5.1924 11.2682 5.4202 11.496L5.83268 11.0835ZM7.17021 13.246C7.398 13.4738 7.76737 13.4738 7.99516 13.246C8.22295 13.0182 8.22295 12.6488 7.99516 12.421L7.17021 13.246ZM11.4993 3.73414C11.2738 3.50404 10.9045 3.5003 10.6744 3.72578C10.4443 3.95127 10.4405 4.32059 10.6661 4.55069L11.4993 3.73414ZM7.58268 3.50016C7.90486 3.50016 8.16602 3.23899 8.16602 2.91683C8.16602 2.59467 7.90486 2.3335 7.58268 2.3335L7.58268 3.50016ZM2.49938 10.2662C2.72486 10.4963 3.09419 10.5 3.32429 10.2745C3.55439 10.0491 3.55814 9.6797 3.33266 9.44964L2.49938 10.2662ZM6.00354 1.57931L7.75354 3.32931L8.57849 2.50435L6.82849 0.754349L6.00354 1.57931ZM7.75354 2.50435L6.00354 4.25435L6.82849 5.07931L8.57849 3.32931L7.75354 2.50435ZM7.17021 8.92102L5.4202 10.671L6.24516 11.496L7.99516 9.74597L7.17021 8.92102ZM5.4202 11.496L7.17021 13.246L7.99516 12.421L6.24516 10.671L5.4202 11.496ZM8.16602 10.5002L6.41602 10.5002V11.6668L8.16602 11.6668V10.5002ZM11.666 7.00016C11.666 8.93316 10.099 10.5002 8.16602 10.5002V11.6668C10.7434 11.6668 12.8327 9.57751 12.8327 7.00016H11.666ZM12.8327 7.00016C12.8327 5.72882 12.3235 4.57524 11.4993 3.73414L10.6661 4.55069C11.2852 5.18256 11.666 6.0463 11.666 7.00016H12.8327ZM5.83268 3.50016H7.58268L7.58268 2.3335H5.83268L5.83268 3.50016ZM2.33268 7.00016C2.33268 5.06717 3.89968 3.50016 5.83268 3.50016L5.83268 2.3335C3.25535 2.3335 1.16602 4.42283 1.16602 7.00016H2.33268ZM1.16602 7.00016C1.16602 8.27148 1.67517 9.42508 2.49938 10.2662L3.33266 9.44964C2.71348 8.81777 2.33268 7.95403 2.33268 7.00016H1.16602Z" fill="white"/>+</g>+</svg>diff --git a/web/app/components/base/icons/assets/vender/workflow/parameter-extractor.svg b/web/app/components/base/icons/assets/vender/workflow/parameter-extractor.svgnew file mode 100644index 00000000000..dc9418b40f1--- /dev/null+++ b/web/app/components/base/icons/assets/vender/workflow/parameter-extractor.svg@@ -0,0 +1,28 @@+<svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">+<g id="icons/parma-extractor">+<path id="Vector" d="M7.58398 10.3543C7.58398 10.0322 7.84514 9.771 8.16732 9.771C8.48949 9.771 8.75065 10.0322 8.75065 10.3543C8.75065 10.6765 8.48949 10.9377 8.16732 10.9377C7.84514 10.9377 7.58398 10.6765 7.58398 10.3543Z" fill="white"/>+<path id="Vector_2" d="M9.625 10.3543C9.625 10.0322 9.88616 9.771 10.2083 9.771C10.5305 9.771 10.7917 10.0322 10.7917 10.3543C10.7917 10.6765 10.5305 10.9377 10.2083 10.9377C9.88616 10.9377 9.625 10.6765 9.625 10.3543Z" fill="white"/>+<path id="Vector_3" d="M7.58398 3.64583C7.58398 3.32366 7.84514 3.0625 8.16732 3.0625C8.48949 3.0625 8.75065 3.32366 8.75065 3.64583C8.75065 3.968 8.48949 4.22917 8.16732 4.22917C7.84514 4.22917 7.58398 3.968 7.58398 3.64583Z" fill="white"/>+<path id="Vector_4" d="M7.72852 12.104C7.72852 11.8624 7.9244 11.6665 8.16602 11.6665C8.40763 11.6665 8.60352 11.8624 8.60352 12.104C8.60352 12.3456 8.40763 12.5415 8.16602 12.5415C7.9244 12.5415 7.72852 12.3456 7.72852 12.104Z" fill="white"/>+<path id="Vector_5" d="M11.375 8.1665C11.375 7.92489 11.5709 7.729 11.8125 7.729C12.0541 7.729 12.25 7.92489 12.25 8.1665C12.25 8.40812 12.0541 8.604 11.8125 8.604C11.5709 8.604 11.375 8.40812 11.375 8.1665Z" fill="white"/>+<path id="Vector_6" d="M11.375 5.8335C11.375 5.59187 11.5709 5.396 11.8125 5.396C12.0541 5.396 12.25 5.59187 12.25 5.8335C12.25 6.07511 12.0541 6.271 11.8125 6.271C11.5709 6.271 11.375 6.07511 11.375 5.8335Z" fill="white"/>+<path id="Vector_7" d="M7.72852 1.896C7.72852 1.65437 7.9244 1.4585 8.16602 1.4585C8.40763 1.4585 8.60352 1.65437 8.60352 1.896C8.60352 2.13762 8.40763 2.3335 8.16602 2.3335C7.9244 2.3335 7.72852 2.13762 7.72852 1.896Z" fill="white"/>+<path id="Vector_8" d="M7.29102 8.1665C7.29102 7.68327 7.68278 7.2915 8.16602 7.2915C8.64925 7.2915 9.04102 7.68327 9.04102 8.1665C9.04102 8.64974 8.64925 9.0415 8.16602 9.0415C7.68278 9.0415 7.29102 8.64974 7.29102 8.1665Z" fill="white"/>+<path id="Vector_9" d="M7.29102 5.8335C7.29102 5.35025 7.68278 4.9585 8.16602 4.9585C8.64925 4.9585 9.04102 5.35025 9.04102 5.8335C9.04102 6.31673 8.64925 6.7085 8.16602 6.7085C7.68278 6.7085 7.29102 6.31673 7.29102 5.8335Z" fill="white"/>+<path id="Vector_10" d="M9.625 8.16683C9.625 7.84465 9.88616 7.5835 10.2083 7.5835C10.5305 7.5835 10.7917 7.84465 10.7917 8.16683C10.7917 8.489 10.5305 8.75016 10.2083 8.75016C9.88616 8.75016 9.625 8.489 9.625 8.16683Z" fill="white"/>+<path id="Vector_11" d="M9.625 5.83333C9.625 5.51116 9.88616 5.25 10.2083 5.25C10.5305 5.25 10.7917 5.51116 10.7917 5.83333C10.7917 6.15551 10.5305 6.41667 10.2083 6.41667C9.88616 6.41667 9.625 6.15551 9.625 5.83333Z" fill="white"/>+<path id="Vector_12" d="M9.625 3.64583C9.625 3.32366 9.88616 3.0625 10.2083 3.0625C10.5305 3.0625 10.7917 3.32366 10.7917 3.64583C10.7917 3.968 10.5305 4.22917 10.2083 4.22917C9.88616 4.22917 9.625 3.968 9.625 3.64583Z" fill="white"/>+<path id="Vector_13" d="M6.41667 3.64583C6.41667 3.968 6.15551 4.22917 5.83333 4.22917C5.51117 4.22917 5.25 3.968 5.25 3.64583C5.25 3.32367 5.51117 3.0625 5.83333 3.0625C6.15551 3.0625 6.41667 3.32367 6.41667 3.64583Z" fill="white"/>+<path id="Vector_14" d="M4.37565 3.64583C4.37565 3.968 4.11448 4.22917 3.79232 4.22917C3.47015 4.22917 3.20898 3.968 3.20898 3.64583C3.20898 3.32367 3.47015 3.0625 3.79232 3.0625C4.11448 3.0625 4.37565 3.32367 4.37565 3.64583Z" fill="white"/>+<path id="Vector_15" d="M6.41667 10.3543C6.41667 10.6765 6.15551 10.9377 5.83333 10.9377C5.51117 10.9377 5.25 10.6765 5.25 10.3543C5.25 10.0322 5.51117 9.771 5.83333 9.771C6.15551 9.771 6.41667 10.0322 6.41667 10.3543Z" fill="white"/>+<path id="Vector_16" d="M6.27148 1.896C6.27148 2.13762 6.0756 2.3335 5.83398 2.3335C5.59236 2.3335 5.39648 2.13762 5.39648 1.896C5.39648 1.65437 5.59236 1.4585 5.83398 1.4585C6.0756 1.4585 6.27148 1.65437 6.27148 1.896Z" fill="white"/>+<path id="Vector_17" d="M2.625 5.8335C2.625 6.07511 2.42912 6.271 2.1875 6.271C1.94588 6.271 1.75 6.07511 1.75 5.8335C1.75 5.59187 1.94588 5.396 2.1875 5.396C2.42912 5.396 2.625 5.59187 2.625 5.8335Z" fill="white"/>+<path id="Vector_18" d="M2.625 8.1665C2.625 8.40812 2.42912 8.604 2.1875 8.604C1.94588 8.604 1.75 8.40812 1.75 8.1665C1.75 7.92489 1.94588 7.729 2.1875 7.729C2.42912 7.729 2.625 7.92489 2.625 8.1665Z" fill="white"/>+<path id="Vector_19" d="M6.27148 12.104C6.27148 12.3456 6.0756 12.5415 5.83398 12.5415C5.59236 12.5415 5.39648 12.3456 5.39648 12.104C5.39648 11.8624 5.59236 11.6665 5.83398 11.6665C6.0756 11.6665 6.27148 11.8624 6.27148 12.104Z" fill="white"/>+<path id="Vector_20" d="M6.70898 5.8335C6.70898 6.31673 6.31722 6.7085 5.83398 6.7085C5.35073 6.7085 4.95898 6.31673 4.95898 5.8335C4.95898 5.35025 5.35073 4.9585 5.83398 4.9585C6.31722 4.9585 6.70898 5.35025 6.70898 5.8335Z" fill="white"/>+<path id="Vector_21" d="M6.70898 8.1665C6.70898 8.64974 6.31722 9.0415 5.83398 9.0415C5.35073 9.0415 4.95898 8.64974 4.95898 8.1665C4.95898 7.68327 5.35073 7.2915 5.83398 7.2915C6.31722 7.2915 6.70898 7.68327 6.70898 8.1665Z" fill="white"/>+<path id="Vector_22" d="M4.37565 5.83333C4.37565 6.15551 4.11448 6.41667 3.79232 6.41667C3.47015 6.41667 3.20898 6.15551 3.20898 5.83333C3.20898 5.51117 3.47015 5.25 3.79232 5.25C4.11448 5.25 4.37565 5.51117 4.37565 5.83333Z" fill="white"/>+<path id="Vector_23" d="M4.37565 8.16683C4.37565 8.489 4.11448 8.75016 3.79232 8.75016C3.47015 8.75016 3.20898 8.489 3.20898 8.16683C3.20898 7.84465 3.47015 7.5835 3.79232 7.5835C4.11448 7.5835 4.37565 7.84465 4.37565 8.16683Z" fill="white"/>+<path id="Vector_24" d="M4.37565 10.3543C4.37565 10.6765 4.11448 10.9377 3.79232 10.9377C3.47015 10.9377 3.20898 10.6765 3.20898 10.3543C3.20898 10.0322 3.47015 9.771 3.79232 9.771C4.11448 9.771 4.37565 10.0322 4.37565 10.3543Z" fill="white"/>+</g>+</svg>diff --git a/web/app/components/base/icons/src/public/common/D.json b/web/app/components/base/icons/src/public/common/D.jsonnew file mode 100644index 00000000000..2090b8909db--- /dev/null+++ b/web/app/components/base/icons/src/public/common/D.json@@ -0,0 +1,125 @@+{+ "icon": {+ "type": "element",+ "isRootNode": true,+ "name": "svg",+ "attributes": {+ "width": "16",+ "height": "16",+ "viewBox": "0 0 16 16",+ "fill": "none",+ "xmlns": "http://www.w3.org/2000/svg"+ },+ "children": [+ {+ "type": "element",+ "name": "path",+ "attributes": {+ "d": "M2 1H7.94339C11.8094 1 14.9434 4.13401 14.9434 8C14.9434 11.866 11.8094 15 7.9434 15H2V1Z",+ "fill": "white"+ },+ "children": []+ },+ {+ "type": "element",+ "name": "path",+ "attributes": {+ "d": "M2 1H7.94339C11.8094 1 14.9434 4.13401 14.9434 8C14.9434 11.866 11.8094 15 7.9434 15H2V1Z",+ "fill": "url(#paint0_angular_19344_240446)"+ },+ "children": []+ },+ {+ "type": "element",+ "name": "path",+ "attributes": {+ "d": "M7.94336 8H8.20751V15H7.94336V8Z",+ "fill": "url(#paint1_linear_19344_240446)"+ },+ "children": []+ },+ {+ "type": "element",+ "name": "defs",+ "attributes": {},+ "children": [+ {+ "type": "element",+ "name": "radialGradient",+ "attributes": {+ "id": "paint0_angular_19344_240446",+ "cx": "0",+ "cy": "0",+ "r": "1",+ "gradientUnits": "userSpaceOnUse",+ "gradientTransform": "translate(7.9434 8) rotate(90) scale(8.75 8.75)"+ },+ "children": [+ {+ "type": "element",+ "name": "stop",+ "attributes": {+ "stop-color": "#001FC2"+ },+ "children": []+ },+ {+ "type": "element",+ "name": "stop",+ "attributes": {+ "offset": "0.711334",+ "stop-color": "#0667F8",+ "stop-opacity": "0.2"+ },+ "children": []+ },+ {+ "type": "element",+ "name": "stop",+ "attributes": {+ "offset": "1",+ "stop-color": "#155EEF",+ "stop-opacity": "0"+ },+ "children": []+ }+ ]+ },+ {+ "type": "element",+ "name": "linearGradient",+ "attributes": {+ "id": "paint1_linear_19344_240446",+ "x1": "8.06244",+ "y1": "8.43754",+ "x2": "7.93744",+ "y2": "9.20317",+ "gradientUnits": "userSpaceOnUse"+ },+ "children": [+ {+ "type": "element",+ "name": "stop",+ "attributes": {+ "stop-color": "white",+ "stop-opacity": "0"+ },+ "children": []+ },+ {+ "type": "element",+ "name": "stop",+ "attributes": {+ "offset": "1",+ "stop-color": "white"+ },+ "children": []+ }+ ]+ }+ ]+ }+ ]+ },+ "name": "D"+}\ No newline at end of filediff --git a/web/app/components/base/icons/src/public/common/D.tsx b/web/app/components/base/icons/src/public/common/D.tsxnew file mode 100644index 00000000000..6d8bbf76539--- /dev/null+++ b/web/app/components/base/icons/src/public/common/D.tsx@@ -0,0 +1,16 @@+// GENERATE BY script+// DON NOT EDIT IT MANUALLY++import * as React from 'react'+import data from './D.json'+import IconBase from '@/app/components/base/icons/IconBase'+import type { IconBaseProps, IconData } from '@/app/components/base/icons/IconBase'++const Icon = React.forwardRef<React.MutableRefObject<SVGElement>, Omit<IconBaseProps, 'data'>>((+ props,+ ref,+) => <IconBase {...props} ref={ref} data={data as IconData} />)++Icon.displayName = 'D'++export default Icondiff --git a/web/app/components/base/icons/src/public/common/index.ts b/web/app/components/base/icons/src/public/common/index.tsindex b65032834b0..b20668175c1 100644--- a/web/app/components/base/icons/src/public/common/index.ts+++ b/web/app/components/base/icons/src/public/common/index.ts@@ -1,3 +1,4 @@+export { default as D } from './D'export { default as DiagonalDividingLine } from './DiagonalDividingLine'export { default as Dify } from './Dify'export { default as Github } from './Github'diff --git a/web/app/components/base/icons/src/vender/line/files/Folder.json b/web/app/components/base/icons/src/vender/line/files/Folder.jsonnew file mode 100644index 00000000000..6bbc4380ae4--- /dev/null+++ b/web/app/components/base/icons/src/vender/line/files/Folder.json@@ -0,0 +1,39 @@+{+ "icon": {+ "type": "element",+ "isRootNode": true,+ "name": "svg",+ "attributes": {+ "width": "14",+ "height": "14",+ "viewBox": "0 0 14 14",+ "fill": "none",+ "xmlns": "http://www.w3.org/2000/svg"+ },+ "children": [+ {+ "type": "element",+ "name": "g",+ "attributes": {+ "id": "folder"+ },+ "children": [+ {+ "type": "element",+ "name": "path",+ "attributes": {+ "id": "Icon",+ "d": "M12.8327 11.0833C12.8327 11.3928 12.7098 11.6895 12.491 11.9083C12.2722 12.1271 11.9754 12.25 11.666 12.25H2.33268C2.02326 12.25 1.72652 12.1271 1.50772 11.9083C1.28893 11.6895 1.16602 11.3928 1.16602 11.0833V2.91667C1.16602 2.60725 1.28893 2.3105 1.50772 2.09171C1.72652 1.87292 2.02326 1.75 2.33268 1.75H5.24935L6.41602 3.5H11.666C11.9754 3.5 12.2722 3.62292 12.491 3.84171C12.7098 4.0605 12.8327 4.35725 12.8327 4.66667V11.0833Z",+ "stroke": "currentColor",+ "stroke-width": "1.5",+ "stroke-linecap": "round",+ "stroke-linejoin": "round"+ },+ "children": []+ }+ ]+ }+ ]+ },+ "name": "Folder"+}\ No newline at end of filediff --git a/web/app/components/base/icons/src/vender/line/files/Folder.tsx b/web/app/components/base/icons/src/vender/line/files/Folder.tsxnew file mode 100644index 00000000000..1914bf6768f--- /dev/null+++ b/web/app/components/base/icons/src/vender/line/files/Folder.tsx@@ -0,0 +1,16 @@+// GENERATE BY script+// DON NOT EDIT IT MANUALLY++import * as React from 'react'+import data from './Folder.json'+import IconBase from '@/app/components/base/icons/IconBase'+import type { IconBaseProps, IconData } from '@/app/components/base/icons/IconBase'++const Icon = React.forwardRef<React.MutableRefObject<SVGElement>, Omit<IconBaseProps, 'data'>>((+ props,+ ref,+) => <IconBase {...props} ref={ref} data={data as IconData} />)++Icon.displayName = 'Folder'++export default Icondiff --git a/web/app/components/base/icons/src/vender/line/files/index.ts b/web/app/components/base/icons/src/vender/line/files/index.tsindex aa057d699a2..05832a9ca5c 100644--- a/web/app/components/base/icons/src/vender/line/files/index.ts+++ b/web/app/components/base/icons/src/vender/line/files/index.ts@@ -7,3 +7,4 @@ export { default as FileDownload02 } from './FileDownload02'export { default as FilePlus01 } from './FilePlus01'export { default as FilePlus02 } from './FilePlus02'export { default as FileText } from './FileText'+export { default as Folder } from './Folder'diff --git a/web/app/components/base/icons/src/vender/line/others/Apps02.json b/web/app/components/base/icons/src/vender/line/others/Apps02.jsonnew file mode 100644index 00000000000..2ff128f24c2--- /dev/null+++ b/web/app/components/base/icons/src/vender/line/others/Apps02.json@@ -0,0 +1,36 @@+{+ "icon": {+ "type": "element",+ "isRootNode": true,+ "name": "svg",+ "attributes": {+ "width": "16",+ "height": "16",+ "viewBox": "0 0 16 16",+ "fill": "none",+ "xmlns": "http://www.w3.org/2000/svg"+ },+ "children": [+ {+ "type": "element",+ "name": "g",+ "attributes": {+ "id": "apps-2-line"+ },+ "children": [+ {+ "type": "element",+ "name": "path",+ "attributes": {+ "id": "Vector",+ "d": "M4.66602 7.6665C3.00916 7.6665 1.66602 6.32336 1.66602 4.6665C1.66602 3.00965 3.00916 1.6665 4.66602 1.6665C6.32287 1.6665 7.66602 3.00965 7.66602 4.6665C7.66602 6.32336 6.32287 7.6665 4.66602 7.6665ZM4.66602 14.3332C3.00916 14.3332 1.66602 12.99 1.66602 11.3332C1.66602 9.6763 3.00916 8.33317 4.66602 8.33317C6.32287 8.33317 7.66602 9.6763 7.66602 11.3332C7.66602 12.99 6.32287 14.3332 4.66602 14.3332ZM11.3327 7.6665C9.67582 7.6665 8.33268 6.32336 8.33268 4.6665C8.33268 3.00965 9.67582 1.6665 11.3327 1.6665C12.9895 1.6665 14.3327 3.00965 14.3327 4.6665C14.3327 6.32336 12.9895 7.6665 11.3327 7.6665ZM11.3327 14.3332C9.67582 14.3332 8.33268 12.99 8.33268 11.3332C8.33268 9.6763 9.67582 8.33317 11.3327 8.33317C12.9895 8.33317 14.3327 9.6763 14.3327 11.3332C14.3327 12.99 12.9895 14.3332 11.3327 14.3332ZM4.66602 6.33317C5.58649 6.33317 6.33268 5.58698 6.33268 4.6665C6.33268 3.74603 5.58649 2.99984 4.66602 2.99984C3.74554 2.99984 2.99935 3.74603 2.99935 4.6665C2.99935 5.58698 3.74554 6.33317 4.66602 6.33317ZM4.66602 12.9998C5.58649 12.9998 6.33268 12.2536 6.33268 11.3332C6.33268 10.4127 5.58649 9.6665 4.66602 9.6665C3.74554 9.6665 2.99935 10.4127 2.99935 11.3332C2.99935 12.2536 3.74554 12.9998 4.66602 12.9998ZM11.3327 6.33317C12.2531 6.33317 12.9993 5.58698 12.9993 4.6665C12.9993 3.74603 12.2531 2.99984 11.3327 2.99984C10.4122 2.99984 9.66602 3.74603 9.66602 4.6665C9.66602 5.58698 10.4122 6.33317 11.3327 6.33317ZM11.3327 12.9998C12.2531 12.9998 12.9993 12.2536 12.9993 11.3332C12.9993 10.4127 12.2531 9.6665 11.3327 9.6665C10.4122 9.6665 9.66602 10.4127 9.66602 11.3332C9.66602 12.2536 10.4122 12.9998 11.3327 12.9998Z",+ "fill": "currentColor"+ },+ "children": []+ }+ ]+ }+ ]+ },+ "name": "Apps02"+}\ No newline at end of filediff --git a/web/app/components/base/icons/src/vender/line/others/Apps02.tsx b/web/app/components/base/icons/src/vender/line/others/Apps02.tsxnew file mode 100644index 00000000000..42109d81dab--- /dev/null+++ b/web/app/components/base/icons/src/vender/line/others/Apps02.tsx@@ -0,0 +1,16 @@+// GENERATE BY script+// DON NOT EDIT IT MANUALLY++import * as React from 'react'+import data from './Apps02.json'+import IconBase from '@/app/components/base/icons/IconBase'+import type { IconBaseProps, IconData } from '@/app/components/base/icons/IconBase'++const Icon = React.forwardRef<React.MutableRefObject<SVGElement>, Omit<IconBaseProps, 'data'>>((+ props,+ ref,+) => <IconBase {...props} ref={ref} data={data as IconData} />)++Icon.displayName = 'Apps02'++export default Icondiff --git a/web/app/components/base/icons/src/vender/line/others/Colors.json b/web/app/components/base/icons/src/vender/line/others/Colors.jsonnew file mode 100644index 00000000000..b1832c2fe8d--- /dev/null+++ b/web/app/components/base/icons/src/vender/line/others/Colors.json@@ -0,0 +1,66 @@+{+ "icon": {+ "type": "element",+ "isRootNode": true,+ "name": "svg",+ "attributes": {+ "width": "14",+ "height": "14",+ "viewBox": "0 0 14 14",+ "fill": "none",+ "xmlns": "http://www.w3.org/2000/svg"+ },+ "children": [+ {+ "type": "element",+ "name": "g",+ "attributes": {+ "id": "colors",+ "clip-path": "url(#clip0_18499_53582)"+ },+ "children": [+ {+ "type": "element",+ "name": "path",+ "attributes": {+ "id": "Icon",+ "d": "M7.00032 11.9422C7.61954 12.4964 8.43724 12.8334 9.33366 12.8334C11.2667 12.8334 12.8337 11.2664 12.8337 9.33342C12.8337 7.71938 11.7411 6.36051 10.2552 5.95602M3.74543 5.95601C2.25954 6.3605 1.16699 7.71937 1.16699 9.33341C1.16699 11.2664 2.734 12.8334 4.66699 12.8334C6.59999 12.8334 8.16699 11.2664 8.16699 9.33341C8.16699 8.87813 8.08006 8.44314 7.92189 8.04415M10.5003 4.66675C10.5003 6.59974 8.93332 8.16675 7.00033 8.16675C5.06733 8.16675 3.50033 6.59974 3.50033 4.66675C3.50033 2.73375 5.06733 1.16675 7.00033 1.16675C8.93332 1.16675 10.5003 2.73375 10.5003 4.66675Z",+ "stroke": "currentColor",+ "stroke-width": "1.25",+ "stroke-linecap": "round",+ "stroke-linejoin": "round"+ },+ "children": []+ }+ ]+ },+ {+ "type": "element",+ "name": "defs",+ "attributes": {},+ "children": [+ {+ "type": "element",+ "name": "clipPath",+ "attributes": {+ "id": "clip0_18499_53582"+ },+ "children": [+ {+ "type": "element",+ "name": "rect",+ "attributes": {+ "width": "14",+ "height": "14",+ "fill": "white"+ },+ "children": []+ }+ ]+ }+ ]+ }+ ]+ },+ "name": "Colors"+}\ No newline at end of filediff --git a/web/app/components/base/icons/src/vender/line/others/Colors.tsx b/web/app/components/base/icons/src/vender/line/others/Colors.tsxnew file mode 100644index 00000000000..224ca116bde--- /dev/null+++ b/web/app/components/base/icons/src/vender/line/others/Colors.tsx@@ -0,0 +1,16 @@+// GENERATE BY script+// DON NOT EDIT IT MANUALLY++import * as React from 'react'+import data from './Colors.json'+import IconBase from '@/app/components/base/icons/IconBase'+import type { IconBaseProps, IconData } from '@/app/components/base/icons/IconBase'++const Icon = React.forwardRef<React.MutableRefObject<SVGElement>, Omit<IconBaseProps, 'data'>>((+ props,+ ref,+) => <IconBase {...props} ref={ref} data={data as IconData} />)++Icon.displayName = 'Colors'++export default Icondiff --git a/web/app/components/base/icons/src/vender/line/others/Exchange02.json b/web/app/components/base/icons/src/vender/line/others/Exchange02.jsonnew file mode 100644index 00000000000..808a9ff644b--- /dev/null+++ b/web/app/components/base/icons/src/vender/line/others/Exchange02.json@@ -0,0 +1,26 @@+{+ "icon": {+ "type": "element",+ "isRootNode": true,+ "name": "svg",+ "attributes": {+ "width": "16",+ "height": "16",+ "viewBox": "0 0 16 16",+ "fill": "none",+ "xmlns": "http://www.w3.org/2000/svg"+ },+ "children": [+ {+ "type": "element",+ "name": "path",+ "attributes": {+ "d": "M4.66602 14.3334C3.00916 14.3334 1.66602 12.9903 1.66602 11.3334C1.66602 9.67655 3.00916 8.33342 4.66602 8.33342C6.32287 8.33342 7.66602 9.67655 7.66602 11.3334C7.66602 12.9903 6.32287 14.3334 4.66602 14.3334ZM11.3327 7.66675C9.67582 7.66675 8.33268 6.3236 8.33268 4.66675C8.33268 3.00989 9.67582 1.66675 11.3327 1.66675C12.9895 1.66675 14.3327 3.00989 14.3327 4.66675C14.3327 6.3236 12.9895 7.66675 11.3327 7.66675ZM4.66602 13.0001C5.58649 13.0001 6.33268 12.2539 6.33268 11.3334C6.33268 10.4129 5.58649 9.66675 4.66602 9.66675C3.74554 9.66675 2.99935 10.4129 2.99935 11.3334C2.99935 12.2539 3.74554 13.0001 4.66602 13.0001ZM11.3327 6.33342C12.2531 6.33342 12.9993 5.58722 12.9993 4.66675C12.9993 3.74627 12.2531 3.00008 11.3327 3.00008C10.4122 3.00008 9.66602 3.74627 9.66602 4.66675C9.66602 5.58722 10.4122 6.33342 11.3327 6.33342ZM1.99935 5.33341C1.99935 3.49247 3.49174 2.00008 5.33268 2.00008H7.33268V3.33341H5.33268C4.22812 3.33341 3.33268 4.22885 3.33268 5.33341V7.33342H1.99935V5.33341ZM13.9993 8.66675H12.666V10.6667C12.666 11.7713 11.7706 12.6667 10.666 12.6667H8.66602V14.0001H10.666C12.5069 14.0001 13.9993 12.5077 13.9993 10.6667V8.66675Z",+ "fill": "currentColor"+ },+ "children": []+ }+ ]+ },+ "name": "Exchange02"+}\ No newline at end of filediff --git a/web/app/components/base/icons/src/vender/line/others/Exchange02.tsx b/web/app/components/base/icons/src/vender/line/others/Exchange02.tsxnew file mode 100644index 00000000000..36fa63e4879--- /dev/null+++ b/web/app/components/base/icons/src/vender/line/others/Exchange02.tsx@@ -0,0 +1,16 @@+// GENERATE BY script+// DON NOT EDIT IT MANUALLY++import * as React from 'react'+import data from './Exchange02.json'+import IconBase from '@/app/components/base/icons/IconBase'+import type { IconBaseProps, IconData } from '@/app/components/base/icons/IconBase'++const Icon = React.forwardRef<React.MutableRefObject<SVGElement>, Omit<IconBaseProps, 'data'>>((+ props,+ ref,+) => <IconBase {...props} ref={ref} data={data as IconData} />)++Icon.displayName = 'Exchange02'++export default Icondiff --git a/web/app/components/base/icons/src/vender/line/others/FileCode.json b/web/app/components/base/icons/src/vender/line/others/FileCode.jsonnew file mode 100644index 00000000000..41050a559b5--- /dev/null+++ b/web/app/components/base/icons/src/vender/line/others/FileCode.json@@ -0,0 +1,26 @@+{+ "icon": {+ "type": "element",+ "isRootNode": true,+ "name": "svg",+ "attributes": {+ "width": "16",+ "height": "16",+ "viewBox": "0 0 16 16",+ "fill": "none",+ "xmlns": "http://www.w3.org/2000/svg"+ },+ "children": [+ {+ "type": "element",+ "name": "path",+ "attributes": {+ "d": "M10 2.66659H3.33333V13.3333H12.6667V5.33325H10V2.66659ZM2 1.99445C2 1.62929 2.29833 1.33325 2.66567 1.33325H10.6667L13.9998 4.66658L14 13.9949C14 14.3659 13.7034 14.6666 13.3377 14.6666H2.66227C2.29651 14.6666 2 14.3631 2 14.0054V1.99445ZM11.7713 7.99992L9.4142 10.3569L8.4714 9.41412L9.8856 7.99992L8.4714 6.58571L9.4142 5.6429L11.7713 7.99992ZM4.22877 7.99992L6.58579 5.6429L7.5286 6.58571L6.11438 7.99992L7.5286 9.41412L6.58579 10.3569L4.22877 7.99992Z",+ "fill": "currentColor"+ },+ "children": []+ }+ ]+ },+ "name": "FileCode"+}\ No newline at end of filediff --git a/web/app/components/base/icons/src/vender/line/others/FileCode.tsx b/web/app/components/base/icons/src/vender/line/others/FileCode.tsxnew file mode 100644index 00000000000..c050f368bbf--- /dev/null+++ b/web/app/components/base/icons/src/vender/line/others/FileCode.tsx@@ -0,0 +1,16 @@+// GENERATE BY script+// DON NOT EDIT IT MANUALLY++import * as React from 'react'+import data from './FileCode.json'+import IconBase from '@/app/components/base/icons/IconBase'+import type { IconBaseProps, IconData } from '@/app/components/base/icons/IconBase'++const Icon = React.forwardRef<React.MutableRefObject<SVGElement>, Omit<IconBaseProps, 'data'>>((+ props,+ ref,+) => <IconBase {...props} ref={ref} data={data as IconData} />)++Icon.displayName = 'FileCode'++export default Icondiff --git a/web/app/components/base/icons/src/vender/line/others/Tools.json b/web/app/components/base/icons/src/vender/line/others/Tools.jsonnew file mode 100644index 00000000000..0ab6857b094--- /dev/null+++ b/web/app/components/base/icons/src/vender/line/others/Tools.json@@ -0,0 +1,119 @@+{+ "icon": {+ "type": "element",+ "isRootNode": true,+ "name": "svg",+ "attributes": {+ "width": "16",+ "height": "17",+ "viewBox": "0 0 16 17",+ "fill": "none",+ "xmlns": "http://www.w3.org/2000/svg"+ },+ "children": [+ {+ "type": "element",+ "name": "g",+ "attributes": {+ "id": "Tools",+ "clip-path": "url(#clip0_5381_39479)"+ },+ "children": [+ {+ "type": "element",+ "name": "path",+ "attributes": {+ "id": "vector",+ "d": "M13.4375 14.4375V6.8125H2.5625V14.4375C2.5625 14.9898 3.01022 15.4375 3.5625 15.4375H12.4375C12.9898 15.4375 13.4375 14.9898 13.4375 14.4375Z",+ "stroke": "currentColor",+ "stroke-width": "1.25",+ "stroke-linecap": "round",+ "stroke-linejoin": "round"+ },+ "children": []+ },+ {+ "type": "element",+ "name": "path",+ "attributes": {+ "id": "vector_2",+ "d": "M13.6254 2.875L11.1738 6.47327",+ "stroke": "currentColor",+ "stroke-width": "1.25",+ "stroke-linecap": "round",+ "stroke-linejoin": "round"+ },+ "children": []+ },+ {+ "type": "element",+ "name": "path",+ "attributes": {+ "id": "vector_3",+ "d": "M6.3125 9.8125H9.6875",+ "stroke": "currentColor",+ "stroke-width": "1.25",+ "stroke-linecap": "round",+ "stroke-linejoin": "round"+ },+ "children": []+ },+ {+ "type": "element",+ "name": "path",+ "attributes": {+ "id": "vector_4",+ "d": "M8.63355 1.88044L8.75 1.64754L8.86645 1.88044C8.97531 2.09816 9.15184 2.27469 9.36956 2.38355L9.60246 2.5L9.36956 2.61645C9.15184 2.72531 8.97531 2.90184 8.86645 3.11956L8.75 3.35246L8.63355 3.11956C8.52469 2.90184 8.34816 2.72531 8.13044 2.61645L7.89754 2.5L8.13044 2.38355C8.34816 2.27469 8.52469 2.09816 8.63355 1.88044Z",+ "stroke": "currentColor",+ "stroke-width": "1.25",+ "stroke-linecap": "square",+ "stroke-linejoin": "round"+ },+ "children": []+ },+ {+ "type": "element",+ "name": "path",+ "attributes": {+ "id": "vector_5",+ "d": "M4.625 3.14754L4.61865 3.16025C4.51946 3.35862 4.35862 3.51946 4.16025 3.61865L4.14754 3.625L4.16025 3.63135C4.35862 3.73054 4.51946 3.89138 4.61865 4.08975L4.625 4.10246L4.63135 4.08975C4.73054 3.89138 4.89138 3.73054 5.08975 3.63135L5.10246 3.625L5.08975 3.61865C4.89138 3.51946 4.73054 3.35862 4.63135 3.16025L4.625 3.14754ZM4.625 3.14754L4.63135 3.16025L4.625 3.14754Z",+ "stroke": "currentColor",+ "stroke-width": "1.25",+ "stroke-linecap": "square",+ "stroke-linejoin": "round"+ },+ "children": []+ }+ ]+ },+ {+ "type": "element",+ "name": "defs",+ "attributes": {},+ "children": [+ {+ "type": "element",+ "name": "clipPath",+ "attributes": {+ "id": "clip0_5381_39479"+ },+ "children": [+ {+ "type": "element",+ "name": "rect",+ "attributes": {+ "width": "16",+ "height": "16",+ "fill": "white",+ "transform": "translate(0 0.5)"+ },+ "children": []+ }+ ]+ }+ ]+ }+ ]+ },+ "name": "Tools"+}\ No newline at end of filediff --git a/web/app/components/base/icons/src/vender/line/others/Tools.tsx b/web/app/components/base/icons/src/vender/line/others/Tools.tsxnew file mode 100644index 00000000000..c46b8bc2b06--- /dev/null+++ b/web/app/components/base/icons/src/vender/line/others/Tools.tsx@@ -0,0 +1,16 @@+// GENERATE BY script+// DON NOT EDIT IT MANUALLY++import * as React from 'react'+import data from './Tools.json'+import IconBase from '@/app/components/base/icons/IconBase'+import type { IconBaseProps, IconData } from '@/app/components/base/icons/IconBase'++const Icon = React.forwardRef<React.MutableRefObject<SVGElement>, Omit<IconBaseProps, 'data'>>((+ props,+ ref,+) => <IconBase {...props} ref={ref} data={data as IconData} />)++Icon.displayName = 'Tools'++export default Icondiff --git a/web/app/components/base/icons/src/vender/line/others/index.ts b/web/app/components/base/icons/src/vender/line/others/index.tsindex 48620ef9e8d..648792f22b4 100644--- a/web/app/components/base/icons/src/vender/line/others/index.ts+++ b/web/app/components/base/icons/src/vender/line/others/index.ts@@ -1 +1,6 @@+export { default as Apps02 } from './Apps02'+export { default as Colors } from './Colors'export { default as DragHandle } from './DragHandle'+export { default as Exchange02 } from './Exchange02'+export { default as FileCode } from './FileCode'+export { default as Tools } from './Tools'diff --git a/web/app/components/base/icons/src/vender/workflow/Iteration.json b/web/app/components/base/icons/src/vender/workflow/Iteration.jsonnew file mode 100644index 00000000000..ee5748d1f10--- /dev/null+++ b/web/app/components/base/icons/src/vender/workflow/Iteration.json@@ -0,0 +1,36 @@+{+ "icon": {+ "type": "element",+ "isRootNode": true,+ "name": "svg",+ "attributes": {+ "width": "14",+ "height": "14",+ "viewBox": "0 0 14 14",+ "fill": "none",+ "xmlns": "http://www.w3.org/2000/svg"+ },+ "children": [+ {+ "type": "element",+ "name": "g",+ "attributes": {+ "id": "icons/iteration"+ },+ "children": [+ {+ "type": "element",+ "name": "path",+ "attributes": {+ "id": "Vector",+ "d": "M6.82849 0.754349C6.6007 0.526545 6.23133 0.526545 6.00354 0.754349C5.77573 0.982158 5.77573 1.3515 6.00354 1.57931L6.82849 0.754349ZM8.16602 2.91683L8.57849 3.32931C8.80628 3.1015 8.80628 2.73216 8.57849 2.50435L8.16602 2.91683ZM6.00354 4.25435C5.77573 4.48216 5.77573 4.8515 6.00354 5.07931C6.23133 5.30711 6.6007 5.30711 6.82849 5.07931L6.00354 4.25435ZM7.99516 9.74597C8.22295 9.51818 8.22295 9.14881 7.99516 8.92102C7.76737 8.69323 7.398 8.69323 7.17021 8.92102L7.99516 9.74597ZM5.83268 11.0835L5.4202 10.671C5.1924 10.8988 5.1924 11.2682 5.4202 11.496L5.83268 11.0835ZM7.17021 13.246C7.398 13.4738 7.76737 13.4738 7.99516 13.246C8.22295 13.0182 8.22295 12.6488 7.99516 12.421L7.17021 13.246ZM11.4993 3.73414C11.2738 3.50404 10.9045 3.5003 10.6744 3.72578C10.4443 3.95127 10.4405 4.32059 10.6661 4.55069L11.4993 3.73414ZM7.58268 3.50016C7.90486 3.50016 8.16602 3.23899 8.16602 2.91683C8.16602 2.59467 7.90486 2.3335 7.58268 2.3335L7.58268 3.50016ZM2.49938 10.2662C2.72486 10.4963 3.09419 10.5 3.32429 10.2745C3.55439 10.0491 3.55814 9.6797 3.33266 9.44964L2.49938 10.2662ZM6.00354 1.57931L7.75354 3.32931L8.57849 2.50435L6.82849 0.754349L6.00354 1.57931ZM7.75354 2.50435L6.00354 4.25435L6.82849 5.07931L8.57849 3.32931L7.75354 2.50435ZM7.17021 8.92102L5.4202 10.671L6.24516 11.496L7.99516 9.74597L7.17021 8.92102ZM5.4202 11.496L7.17021 13.246L7.99516 12.421L6.24516 10.671L5.4202 11.496ZM8.16602 10.5002L6.41602 10.5002V11.6668L8.16602 11.6668V10.5002ZM11.666 7.00016C11.666 8.93316 10.099 10.5002 8.16602 10.5002V11.6668C10.7434 11.6668 12.8327 9.57751 12.8327 7.00016H11.666ZM12.8327 7.00016C12.8327 5.72882 12.3235 4.57524 11.4993 3.73414L10.6661 4.55069C11.2852 5.18256 11.666 6.0463 11.666 7.00016H12.8327ZM5.83268 3.50016H7.58268L7.58268 2.3335H5.83268L5.83268 3.50016ZM2.33268 7.00016C2.33268 5.06717 3.89968 3.50016 5.83268 3.50016L5.83268 2.3335C3.25535 2.3335 1.16602 4.42283 1.16602 7.00016H2.33268ZM1.16602 7.00016C1.16602 8.27148 1.67517 9.42508 2.49938 10.2662L3.33266 9.44964C2.71348 8.81777 2.33268 7.95403 2.33268 7.00016H1.16602Z",+ "fill": "currentColor"+ },+ "children": []+ }+ ]+ }+ ]+ },+ "name": "Iteration"+}\ No newline at end of filediff --git a/web/app/components/base/icons/src/vender/workflow/Iteration.tsx b/web/app/components/base/icons/src/vender/workflow/Iteration.tsxnew file mode 100644index 00000000000..57b6a882d6f--- /dev/null+++ b/web/app/components/base/icons/src/vender/workflow/Iteration.tsx@@ -0,0 +1,16 @@+// GENERATE BY script+// DON NOT EDIT IT MANUALLY++import * as React from 'react'+import data from './Iteration.json'+import IconBase from '@/app/components/base/icons/IconBase'+import type { IconBaseProps, IconData } from '@/app/components/base/icons/IconBase'++const Icon = React.forwardRef<React.MutableRefObject<SVGElement>, Omit<IconBaseProps, 'data'>>((+ props,+ ref,+) => <IconBase {...props} ref={ref} data={data as IconData} />)++Icon.displayName = 'Iteration'++export default Icondiff --git a/web/app/components/base/icons/src/vender/workflow/IterationStart.json b/web/app/components/base/icons/src/vender/workflow/IterationStart.jsonnew file mode 100644index 00000000000..2941cdb65d4--- /dev/null+++ b/web/app/components/base/icons/src/vender/workflow/IterationStart.json@@ -0,0 +1,36 @@+{+ "icon": {+ "type": "element",+ "isRootNode": true,+ "name": "svg",+ "attributes": {+ "width": "12",+ "height": "12",+ "viewBox": "0 0 12 12",+ "fill": "none",+ "xmlns": "http://www.w3.org/2000/svg"+ },+ "children": [+ {+ "type": "element",+ "name": "g",+ "attributes": {+ "id": "icons/block-start"+ },+ "children": [+ {+ "type": "element",+ "name": "path",+ "attributes": {+ "id": "Vector",+ "d": "M6.8498 1.72732C6.3379 1.3754 5.6621 1.3754 5.1502 1.72732L2.1502 3.78982C1.74317 4.06965 1.5 4.53193 1.5 5.02588V8.99983C1.5 9.82828 2.17158 10.4998 3 10.4998H4.25C4.52614 10.4998 4.75 10.276 4.75 9.99983V8.24983C4.75 7.55948 5.30965 6.99983 6 6.99983C6.69035 6.99983 7.25 7.55948 7.25 8.24983V9.99983C7.25 10.276 7.47385 10.4998 7.75 10.4998H9C9.82845 10.4998 10.5 9.82828 10.5 8.99983V5.02588C10.5 4.53193 10.2568 4.06965 9.8498 3.78982L6.8498 1.72732Z",+ "fill": "currentColor"+ },+ "children": []+ }+ ]+ }+ ]+ },+ "name": "IterationStart"+}\ No newline at end of filediff --git a/web/app/components/base/icons/src/vender/workflow/IterationStart.tsx b/web/app/components/base/icons/src/vender/workflow/IterationStart.tsxnew file mode 100644index 00000000000..6a9155a1f13--- /dev/null+++ b/web/app/components/base/icons/src/vender/workflow/IterationStart.tsx@@ -0,0 +1,16 @@+// GENERATE BY script+// DON NOT EDIT IT MANUALLY++import * as React from 'react'+import data from './IterationStart.json'+import IconBase from '@/app/components/base/icons/IconBase'+import type { IconBaseProps, IconData } from '@/app/components/base/icons/IconBase'++const Icon = React.forwardRef<React.MutableRefObject<SVGElement>, Omit<IconBaseProps, 'data'>>((+ props,+ ref,+) => <IconBase {...props} ref={ref} data={data as IconData} />)++Icon.displayName = 'IterationStart'++export default Icondiff --git a/web/app/components/base/icons/src/vender/workflow/ParameterExtractor.json b/web/app/components/base/icons/src/vender/workflow/ParameterExtractor.jsonnew file mode 100644index 00000000000..7d4fa6424ad--- /dev/null+++ b/web/app/components/base/icons/src/vender/workflow/ParameterExtractor.json@@ -0,0 +1,266 @@+{+ "icon": {+ "type": "element",+ "isRootNode": true,+ "name": "svg",+ "attributes": {+ "width": "14",+ "height": "14",+ "viewBox": "0 0 14 14",+ "fill": "none",+ "xmlns": "http://www.w3.org/2000/svg"+ },+ "children": [+ {+ "type": "element",+ "name": "g",+ "attributes": {+ "id": "icons/parma-extractor"+ },+ "children": [+ {+ "type": "element",+ "name": "path",+ "attributes": {+ "id": "Vector",+ "d": "M7.58398 10.3543C7.58398 10.0322 7.84514 9.771 8.16732 9.771C8.48949 9.771 8.75065 10.0322 8.75065 10.3543C8.75065 10.6765 8.48949 10.9377 8.16732 10.9377C7.84514 10.9377 7.58398 10.6765 7.58398 10.3543Z",+ "fill": "currentColor"+ },+ "children": []+ },+ {+ "type": "element",+ "name": "path",+ "attributes": {+ "id": "Vector_2",+ "d": "M9.625 10.3543C9.625 10.0322 9.88616 9.771 10.2083 9.771C10.5305 9.771 10.7917 10.0322 10.7917 10.3543C10.7917 10.6765 10.5305 10.9377 10.2083 10.9377C9.88616 10.9377 9.625 10.6765 9.625 10.3543Z",+ "fill": "currentColor"+ },+ "children": []+ },+ {+ "type": "element",+ "name": "path",+ "attributes": {+ "id": "Vector_3",+ "d": "M7.58398 3.64583C7.58398 3.32366 7.84514 3.0625 8.16732 3.0625C8.48949 3.0625 8.75065 3.32366 8.75065 3.64583C8.75065 3.968 8.48949 4.22917 8.16732 4.22917C7.84514 4.22917 7.58398 3.968 7.58398 3.64583Z",+ "fill": "currentColor"+ },+ "children": []+ },+ {+ "type": "element",+ "name": "path",+ "attributes": {+ "id": "Vector_4",+ "d": "M7.72852 12.104C7.72852 11.8624 7.9244 11.6665 8.16602 11.6665C8.40763 11.6665 8.60352 11.8624 8.60352 12.104C8.60352 12.3456 8.40763 12.5415 8.16602 12.5415C7.9244 12.5415 7.72852 12.3456 7.72852 12.104Z",+ "fill": "currentColor"+ },+ "children": []+ },+ {+ "type": "element",+ "name": "path",+ "attributes": {+ "id": "Vector_5",+ "d": "M11.375 8.1665C11.375 7.92489 11.5709 7.729 11.8125 7.729C12.0541 7.729 12.25 7.92489 12.25 8.1665C12.25 8.40812 12.0541 8.604 11.8125 8.604C11.5709 8.604 11.375 8.40812 11.375 8.1665Z",+ "fill": "currentColor"+ },+ "children": []+ },+ {+ "type": "element",+ "name": "path",+ "attributes": {+ "id": "Vector_6",+ "d": "M11.375 5.8335C11.375 5.59187 11.5709 5.396 11.8125 5.396C12.0541 5.396 12.25 5.59187 12.25 5.8335C12.25 6.07511 12.0541 6.271 11.8125 6.271C11.5709 6.271 11.375 6.07511 11.375 5.8335Z",+ "fill": "currentColor"+ },+ "children": []+ },+ {+ "type": "element",+ "name": "path",+ "attributes": {+ "id": "Vector_7",+ "d": "M7.72852 1.896C7.72852 1.65437 7.9244 1.4585 8.16602 1.4585C8.40763 1.4585 8.60352 1.65437 8.60352 1.896C8.60352 2.13762 8.40763 2.3335 8.16602 2.3335C7.9244 2.3335 7.72852 2.13762 7.72852 1.896Z",+ "fill": "currentColor"+ },+ "children": []+ },+ {+ "type": "element",+ "name": "path",+ "attributes": {+ "id": "Vector_8",+ "d": "M7.29102 8.1665C7.29102 7.68327 7.68278 7.2915 8.16602 7.2915C8.64925 7.2915 9.04102 7.68327 9.04102 8.1665C9.04102 8.64974 8.64925 9.0415 8.16602 9.0415C7.68278 9.0415 7.29102 8.64974 7.29102 8.1665Z",+ "fill": "currentColor"+ },+ "children": []+ },+ {+ "type": "element",+ "name": "path",+ "attributes": {+ "id": "Vector_9",+ "d": "M7.29102 5.8335C7.29102 5.35025 7.68278 4.9585 8.16602 4.9585C8.64925 4.9585 9.04102 5.35025 9.04102 5.8335C9.04102 6.31673 8.64925 6.7085 8.16602 6.7085C7.68278 6.7085 7.29102 6.31673 7.29102 5.8335Z",+ "fill": "currentColor"+ },+ "children": []+ },+ {+ "type": "element",+ "name": "path",+ "attributes": {+ "id": "Vector_10",+ "d": "M9.625 8.16683C9.625 7.84465 9.88616 7.5835 10.2083 7.5835C10.5305 7.5835 10.7917 7.84465 10.7917 8.16683C10.7917 8.489 10.5305 8.75016 10.2083 8.75016C9.88616 8.75016 9.625 8.489 9.625 8.16683Z",+ "fill": "currentColor"+ },+ "children": []+ },+ {+ "type": "element",+ "name": "path",+ "attributes": {+ "id": "Vector_11",+ "d": "M9.625 5.83333C9.625 5.51116 9.88616 5.25 10.2083 5.25C10.5305 5.25 10.7917 5.51116 10.7917 5.83333C10.7917 6.15551 10.5305 6.41667 10.2083 6.41667C9.88616 6.41667 9.625 6.15551 9.625 5.83333Z",+ "fill": "currentColor"+ },+ "children": []+ },+ {+ "type": "element",+ "name": "path",+ "attributes": {+ "id": "Vector_12",+ "d": "M9.625 3.64583C9.625 3.32366 9.88616 3.0625 10.2083 3.0625C10.5305 3.0625 10.7917 3.32366 10.7917 3.64583C10.7917 3.968 10.5305 4.22917 10.2083 4.22917C9.88616 4.22917 9.625 3.968 9.625 3.64583Z",+ "fill": "currentColor"+ },+ "children": []+ },+ {+ "type": "element",+ "name": "path",+ "attributes": {+ "id": "Vector_13",+ "d": "M6.41667 3.64583C6.41667 3.968 6.15551 4.22917 5.83333 4.22917C5.51117 4.22917 5.25 3.968 5.25 3.64583C5.25 3.32367 5.51117 3.0625 5.83333 3.0625C6.15551 3.0625 6.41667 3.32367 6.41667 3.64583Z",+ "fill": "currentColor"+ },+ "children": []+ },+ {+ "type": "element",+ "name": "path",+ "attributes": {+ "id": "Vector_14",+ "d": "M4.37565 3.64583C4.37565 3.968 4.11448 4.22917 3.79232 4.22917C3.47015 4.22917 3.20898 3.968 3.20898 3.64583C3.20898 3.32367 3.47015 3.0625 3.79232 3.0625C4.11448 3.0625 4.37565 3.32367 4.37565 3.64583Z",+ "fill": "currentColor"+ },+ "children": []+ },+ {+ "type": "element",+ "name": "path",+ "attributes": {+ "id": "Vector_15",+ "d": "M6.41667 10.3543C6.41667 10.6765 6.15551 10.9377 5.83333 10.9377C5.51117 10.9377 5.25 10.6765 5.25 10.3543C5.25 10.0322 5.51117 9.771 5.83333 9.771C6.15551 9.771 6.41667 10.0322 6.41667 10.3543Z",+ "fill": "currentColor"+ },+ "children": []+ },+ {+ "type": "element",+ "name": "path",+ "attributes": {+ "id": "Vector_16",+ "d": "M6.27148 1.896C6.27148 2.13762 6.0756 2.3335 5.83398 2.3335C5.59236 2.3335 5.39648 2.13762 5.39648 1.896C5.39648 1.65437 5.59236 1.4585 5.83398 1.4585C6.0756 1.4585 6.27148 1.65437 6.27148 1.896Z",+ "fill": "currentColor"+ },+ "children": []+ },+ {+ "type": "element",+ "name": "path",+ "attributes": {+ "id": "Vector_17",+ "d": "M2.625 5.8335C2.625 6.07511 2.42912 6.271 2.1875 6.271C1.94588 6.271 1.75 6.07511 1.75 5.8335C1.75 5.59187 1.94588 5.396 2.1875 5.396C2.42912 5.396 2.625 5.59187 2.625 5.8335Z",+ "fill": "currentColor"+ },+ "children": []+ },+ {+ "type": "element",+ "name": "path",+ "attributes": {+ "id": "Vector_18",+ "d": "M2.625 8.1665C2.625 8.40812 2.42912 8.604 2.1875 8.604C1.94588 8.604 1.75 8.40812 1.75 8.1665C1.75 7.92489 1.94588 7.729 2.1875 7.729C2.42912 7.729 2.625 7.92489 2.625 8.1665Z",+ "fill": "currentColor"+ },+ "children": []+ },+ {+ "type": "element",+ "name": "path",+ "attributes": {+ "id": "Vector_19",+ "d": "M6.27148 12.104C6.27148 12.3456 6.0756 12.5415 5.83398 12.5415C5.59236 12.5415 5.39648 12.3456 5.39648 12.104C5.39648 11.8624 5.59236 11.6665 5.83398 11.6665C6.0756 11.6665 6.27148 11.8624 6.27148 12.104Z",+ "fill": "currentColor"+ },+ "children": []+ },+ {+ "type": "element",+ "name": "path",+ "attributes": {+ "id": "Vector_20",+ "d": "M6.70898 5.8335C6.70898 6.31673 6.31722 6.7085 5.83398 6.7085C5.35073 6.7085 4.95898 6.31673 4.95898 5.8335C4.95898 5.35025 5.35073 4.9585 5.83398 4.9585C6.31722 4.9585 6.70898 5.35025 6.70898 5.8335Z",+ "fill": "currentColor"+ },+ "children": []+ },+ {+ "type": "element",+ "name": "path",+ "attributes": {+ "id": "Vector_21",+ "d": "M6.70898 8.1665C6.70898 8.64974 6.31722 9.0415 5.83398 9.0415C5.35073 9.0415 4.95898 8.64974 4.95898 8.1665C4.95898 7.68327 5.35073 7.2915 5.83398 7.2915C6.31722 7.2915 6.70898 7.68327 6.70898 8.1665Z",+ "fill": "currentColor"+ },+ "children": []+ },+ {+ "type": "element",+ "name": "path",+ "attributes": {+ "id": "Vector_22",+ "d": "M4.37565 5.83333C4.37565 6.15551 4.11448 6.41667 3.79232 6.41667C3.47015 6.41667 3.20898 6.15551 3.20898 5.83333C3.20898 5.51117 3.47015 5.25 3.79232 5.25C4.11448 5.25 4.37565 5.51117 4.37565 5.83333Z",+ "fill": "currentColor"+ },+ "children": []+ },+ {+ "type": "element",+ "name": "path",+ "attributes": {+ "id": "Vector_23",+ "d": "M4.37565 8.16683C4.37565 8.489 4.11448 8.75016 3.79232 8.75016C3.47015 8.75016 3.20898 8.489 3.20898 8.16683C3.20898 7.84465 3.47015 7.5835 3.79232 7.5835C4.11448 7.5835 4.37565 7.84465 4.37565 8.16683Z",+ "fill": "currentColor"+ },+ "children": []+ },+ {+ "type": "element",+ "name": "path",+ "attributes": {+ "id": "Vector_24",+ "d": "M4.37565 10.3543C4.37565 10.6765 4.11448 10.9377 3.79232 10.9377C3.47015 10.9377 3.20898 10.6765 3.20898 10.3543C3.20898 10.0322 3.47015 9.771 3.79232 9.771C4.11448 9.771 4.37565 10.0322 4.37565 10.3543Z",+ "fill": "currentColor"+ },+ "children": []+ }+ ]+ }+ ]+ },+ "name": "ParameterExtractor"+}\ No newline at end of filediff --git a/web/app/components/base/icons/src/vender/workflow/ParameterExtractor.tsx b/web/app/components/base/icons/src/vender/workflow/ParameterExtractor.tsxnew file mode 100644index 00000000000..f080f5aaeff--- /dev/null+++ b/web/app/components/base/icons/src/vender/workflow/ParameterExtractor.tsx@@ -0,0 +1,16 @@+// GENERATE BY script+// DON NOT EDIT IT MANUALLY++import * as React from 'react'+import data from './ParameterExtractor.json'+import IconBase from '@/app/components/base/icons/IconBase'+import type { IconBaseProps, IconData } from '@/app/components/base/icons/IconBase'++const Icon = React.forwardRef<React.MutableRefObject<SVGElement>, Omit<IconBaseProps, 'data'>>((+ props,+ ref,+) => <IconBase {...props} ref={ref} data={data as IconData} />)++Icon.displayName = 'ParameterExtractor'++export default Icondiff --git a/web/app/components/base/icons/src/vender/workflow/index.ts b/web/app/components/base/icons/src/vender/workflow/index.tsindex bb79b2c0459..94e20ae6a9e 100644--- a/web/app/components/base/icons/src/vender/workflow/index.ts+++ b/web/app/components/base/icons/src/vender/workflow/index.ts@@ -4,9 +4,12 @@ export { default as End } from './End'export { default as Home } from './Home'export { default as Http } from './Http'export { default as IfElse } from './IfElse'+export { default as IterationStart } from './IterationStart'+export { default as Iteration } from './Iteration'export { default as Jinja } from './Jinja'export { default as KnowledgeRetrieval } from './KnowledgeRetrieval'export { default as Llm } from './Llm'+export { default as ParameterExtractor } from './ParameterExtractor'export { default as QuestionClassifier } from './QuestionClassifier'export { default as TemplatingTransform } from './TemplatingTransform'export { default as VariableX } from './VariableX'diff --git a/web/app/components/base/message-log-modal/index.tsx b/web/app/components/base/message-log-modal/index.tsxindex 4c389f7e10e..3b3d626737e 100644--- a/web/app/components/base/message-log-modal/index.tsx+++ b/web/app/components/base/message-log-modal/index.tsx@@ -1,20 +1,24 @@import type { FC } from 'react'import { useTranslation } from 'react-i18next'import cn from 'classnames'-import { useEffect, useRef, useState } from 'react'-import { useClickAway } from 'ahooks'+import { useCallback, useEffect, useRef, useState } from 'react'+import { useBoolean, useClickAway } from 'ahooks'+import IterationResultPanel from '../../workflow/run/iteration-result-panel'import { XClose } from '@/app/components/base/icons/src/vender/line/general'import type { IChatItem } from '@/app/components/app/chat/type'import Run from '@/app/components/workflow/run'+import type { NodeTracing } from '@/types/workflow'type MessageLogModalProps = {currentLogItem?: IChatItem+ defaultTab?: stringwidth: numberfixedWidth?: booleanonCancel: () => void}const MessageLogModal: FC<MessageLogModalProps> = ({currentLogItem,+ defaultTab = 'DETAIL',width,fixedWidth,onCancel,@@ -32,6 +36,17 @@ const MessageLogModal: FC<MessageLogModalProps> = ({setMounted(true)}, [])+ const [iterationRunResult, setIterationRunResult] = useState<NodeTracing[][]>([])+ const [isShowIterationDetail, {+ setTrue: doShowIterationDetail,+ setFalse: doHideIterationDetail,+ }] = useBoolean(false)++ const handleShowIterationDetail = useCallback((detail: NodeTracing[][]) => {+ setIterationRunResult(detail)+ doShowIterationDetail()+ }, [doShowIterationDetail])+if (!currentLogItem || !currentLogItem.workflow_run_id)return null@@ -53,11 +68,28 @@ const MessageLogModal: FC<MessageLogModalProps> = ({}}ref={ref}>- <h1 className='shrink-0 px-4 py-1 text-md font-semibold text-gray-900'>{t('appLog.runDetail.title')}</h1>- <span className='absolute right-3 top-4 p-1 cursor-pointer z-20' onClick={onCancel}>- <XClose className='w-4 h-4 text-gray-500' />- </span>- <Run hideResult activeTab='DETAIL' runID={currentLogItem.workflow_run_id}/>+ {isShowIterationDetail+ ? (+ <IterationResultPanel+ list={iterationRunResult}+ onHide={doHideIterationDetail}+ onBack={doHideIterationDetail}+ />+ )+ : (+ <>+ <h1 className='shrink-0 px-4 py-1 text-md font-semibold text-gray-900'>{t('appLog.runDetail.title')}</h1>+ <span className='absolute right-3 top-4 p-1 cursor-pointer z-20' onClick={onCancel}>+ <XClose className='w-4 h-4 text-gray-500' />+ </span>+ <Run+ hideResult activeTab={defaultTab as any}+ runID={currentLogItem.workflow_run_id}+ onShowIterationDetail={handleShowIterationDetail}+ />+ </>+ )}+</div>)}diff --git a/web/app/components/base/panel/index.tsx b/web/app/components/base/panel/index.tsxdeleted file mode 100644index 11de390fd7e..00000000000--- a/web/app/components/base/panel/index.tsx+++ /dev/null@@ -1,78 +0,0 @@-'use client'-import type { FC } from 'react'-import React, { useEffect } from 'react'-import cn from 'classnames'-import { useBoolean } from 'ahooks'-import { ChevronRightIcon } from '@heroicons/react/24/outline'--export type IPanelProps = {- className?: string- headerIcon: React.ReactNode- title: React.ReactNode- headerRight?: React.ReactNode- bodyClassName?: string- children: React.ReactNode- keepUnFold?: boolean- foldDisabled?: boolean- onFoldChange?: (fold: boolean) => void- controlUnFold?: number- controlFold?: number-}--const Panel: FC<IPanelProps> = ({- className,- headerIcon,- title,- headerRight,- bodyClassName,- children,- keepUnFold,- foldDisabled = false,- onFoldChange,- controlUnFold,- controlFold,-}) => {- const [fold, { setTrue: setFold, setFalse: setUnFold, toggle: toggleFold }] = useBoolean(!keepUnFold)- useEffect(() => {- onFoldChange?.(fold)- }, [fold])-- useEffect(() => {- if (controlUnFold)- setUnFold()- }, [controlUnFold])-- useEffect(() => {- if (controlFold)- setFold()- }, [controlFold])-- // overflow-hidden- return (- <div className={cn(className, 'w-full rounded-xl border border-gray-100 overflow-hidden select-none')}>- {/* Header */}- <div- onClick={() => (!foldDisabled && !keepUnFold) && toggleFold()}- className={cn(!fold && 'border-b border-gray-100', 'flex justify-between items-center h-12 bg-gray-50 pl-4 pr-2')}>- <div className='flex items-center gap-2'>- {headerIcon}- <div className='text-gray-900 text-sm'>{title}</div>- </div>- {(fold && headerRight) ? headerRight : ''}- {!headerRight && !keepUnFold && (- <ChevronRightIcon className={cn(!fold && 'rotate-90', 'mr-2 cursor-pointer')} width="16" height="16">- </ChevronRightIcon>- )}- </div>-- {/* Main Content */}-- {!fold && !foldDisabled && (- <div className={cn(bodyClassName)}>- {children}- </div>- )}- </div>- )-}-export default React.memo(Panel)diff --git a/web/app/components/base/portal-to-follow-elem/index.tsx b/web/app/components/base/portal-to-follow-elem/index.tsxindex 46f4e1a40fe..24d30eb5263 100644--- a/web/app/components/base/portal-to-follow-elem/index.tsx+++ b/web/app/components/base/portal-to-follow-elem/index.tsx@@ -150,8 +150,10 @@ React.HTMLProps<HTMLDivElement>if (!context.open)return null+ const body = document.body+return (- <FloatingPortal>+ <FloatingPortal root={body}><divref={ref}style={{diff --git a/web/app/components/base/prompt-editor/plugins/workflow-variable-block/component.tsx b/web/app/components/base/prompt-editor/plugins/workflow-variable-block/component.tsxindex eb2aa0be6c5..e5806d42b7b 100644--- a/web/app/components/base/prompt-editor/plugins/workflow-variable-block/component.tsx+++ b/web/app/components/base/prompt-editor/plugins/workflow-variable-block/component.tsx@@ -39,7 +39,13 @@ const WorkflowVariableBlockComponent = ({const [editor] = useLexicalComposerContext()const [ref, isSelected] = useSelectOrDelete(nodeKey, DELETE_WORKFLOW_VARIABLE_BLOCK_COMMAND)const variablesLength = variables.length- const lastVariable = isSystemVar(variables) ? variables.join('.') : variables[variablesLength - 1]+ const varName = (+ () => {+ const isSystem = isSystemVar(variables)+ const varName = variablesLength >= 3 ? (variables).slice(-2).join('.') : variables[variablesLength - 1]+ return `${isSystem ? 'sys.' : ''}${varName}`+ }+ )()const [localWorkflowNodesMap, setLocalWorkflowNodesMap] = useState<WorkflowNodesMap>(workflowNodesMap)const node = localWorkflowNodesMap![variables[0]]@@ -86,7 +92,7 @@ const WorkflowVariableBlockComponent = ({</div><div className='flex items-center text-primary-600'><Variable02 className='w-3.5 h-3.5' />- <div className='shrink-0 ml-0.5 text-xs font-medium truncate' title={lastVariable}>{lastVariable}</div>+ <div className='shrink-0 ml-0.5 text-xs font-medium truncate' title={varName}>{varName}</div>{!node && (<AlertCircle className='ml-0.5 w-3 h-3 text-[#D92D20]' />diff --git a/web/app/components/base/select/index.tsx b/web/app/components/base/select/index.tsxindex 1b40b27b0a0..503aeab6354 100644--- a/web/app/components/base/select/index.tsx+++ b/web/app/components/base/select/index.tsx@@ -37,6 +37,7 @@ export type ISelectProps = {bgClassName?: stringplaceholder?: stringoverlayClassName?: string+ optionClassName?: string}const Select: FC<ISelectProps> = ({className,@@ -47,6 +48,7 @@ const Select: FC<ISelectProps> = ({allowSearch = true,bgClassName = 'bg-gray-100',overlayClassName,+ optionClassName,}) => {const [query, setQuery] = useState('')const [open, setOpen] = useState(false)@@ -97,7 +99,7 @@ const Select: FC<ISelectProps> = ({if (!disabled)setOpen(!open)}- } className={`flex items-center h-9 w-full rounded-lg border-0 ${bgClassName} py-1.5 pl-3 pr-10 shadow-sm sm:text-sm sm:leading-6 focus-visible:outline-none focus-visible:bg-gray-200 group-hover:bg-gray-200`}>+ } className={classNames(optionClassName, `flex items-center h-9 w-full rounded-lg border-0 ${bgClassName} py-1.5 pl-3 pr-10 shadow-sm sm:text-sm sm:leading-6 focus-visible:outline-none focus-visible:bg-gray-200 group-hover:bg-gray-200`)}><div className='w-0 grow text-left truncate' title={selectedItem?.name}>{selectedItem?.name}</div></Combobox.Button>}<Combobox.Button className="absolute inset-y-0 right-0 flex items-center rounded-r-md px-2 focus:outline-none group-hover:bg-gray-200" onClick={@@ -118,6 +120,7 @@ const Select: FC<ISelectProps> = ({value={item}className={({ active }: { active: boolean }) =>classNames(+ optionClassName,'relative cursor-default select-none py-2 pl-3 pr-9 rounded-lg hover:bg-gray-100 text-gray-700',active ? 'bg-gray-100' : '',)diff --git a/web/app/components/header/HeaderWrapper.tsx b/web/app/components/header/HeaderWrapper.tsxindex e0f6cfc1115..ba51216dd7d 100644--- a/web/app/components/header/HeaderWrapper.tsx+++ b/web/app/components/header/HeaderWrapper.tsx@@ -11,7 +11,7 @@ const HeaderWrapper = ({children,}: HeaderWrapperProps) => {const pathname = usePathname()- const isBordered = ['/apps', '/datasets', '/datasets/create'].includes(pathname)+ const isBordered = ['/apps', '/datasets', '/datasets/create', '/tools'].includes(pathname)return (<div className={classNames(diff --git a/web/app/components/header/account-setting/model-provider-page/declarations.ts b/web/app/components/header/account-setting/model-provider-page/declarations.tsindex e7d799ff9b4..9e6ee51d3d8 100644--- a/web/app/components/header/account-setting/model-provider-page/declarations.ts+++ b/web/app/components/header/account-setting/model-provider-page/declarations.ts@@ -12,6 +12,7 @@ export enum FormTypeEnum {secretInput = 'secret-input',select = 'select',radio = 'radio',+ files = 'files',}export type FormOption = {diff --git a/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/index.tsx b/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/index.tsxindex f6557a00c37..65e770b998c 100644--- a/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/index.tsx+++ b/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/index.tsx@@ -239,7 +239,7 @@ const ModelParameterModal: FC<ModelParameterModalProps> = ({key={`${modelId}-${parameter.name}`}className='mb-4'parameterRule={parameter}- value={completionParams[parameter.name]}+ value={completionParams?.[parameter.name]}onChange={v => handleParamChange(parameter.name, v)}onSwitch={(checked, assignValue) => handleSwitch(parameter.name, checked, assignValue)}isInWorkflow={isInWorkflow}diff --git a/web/app/components/share/text-generation/result/index.tsx b/web/app/components/share/text-generation/result/index.tsxindex cf6c31c6c32..9272c20548f 100644--- a/web/app/components/share/text-generation/result/index.tsx+++ b/web/app/components/share/text-generation/result/index.tsx@@ -192,6 +192,8 @@ const Result: FC<IResultProps> = ({})()if (isWorkflow) {+ let isInIteration = false+sendWorkflowMessage(data,{@@ -205,7 +207,34 @@ const Result: FC<IResultProps> = ({})setRespondingFalse()},+ onIterationStart: ({ data }) => {+ setWorkflowProccessData(produce(getWorkflowProccessData()!, (draft) => {+ draft.expand = true+ draft.tracing!.push({+ ...data,+ status: NodeRunningStatus.Running,+ expand: true,+ } as any)+ }))+ isInIteration = true+ },+ onIterationNext: () => {+ },+ onIterationFinish: ({ data }) => {+ setWorkflowProccessData(produce(getWorkflowProccessData()!, (draft) => {+ draft.expand = true+ // const iteration = draft.tracing![draft.tracing!.length - 1]+ draft.tracing![draft.tracing!.length - 1] = {+ ...data,+ expand: !!data.error,+ } as any+ }))+ isInIteration = false+ },onNodeStarted: ({ data }) => {+ if (isInIteration)+ return+setWorkflowProccessData(produce(getWorkflowProccessData()!, (draft) => {draft.expand = truedraft.tracing!.push({@@ -216,6 +245,9 @@ const Result: FC<IResultProps> = ({}))},onNodeFinished: ({ data }) => {+ if (isInIteration)+ return+setWorkflowProccessData(produce(getWorkflowProccessData()!, (draft) => {const currentIndex = draft.tracing!.findIndex(trace => trace.node_id === data.node_id)if (currentIndex > -1 && draft.tracing) {diff --git a/web/app/components/tools/add-tool-modal/D.png b/web/app/components/tools/add-tool-modal/D.pngnew file mode 100644index 00000000000..70b829c821fBinary files /dev/null and b/web/app/components/tools/add-tool-modal/D.png differdiff --git a/web/app/components/tools/add-tool-modal/category.tsx b/web/app/components/tools/add-tool-modal/category.tsxnew file mode 100644index 00000000000..e40a735f0f3--- /dev/null+++ b/web/app/components/tools/add-tool-modal/category.tsx@@ -0,0 +1,70 @@+'use client'+import { useRef } from 'react'+import cn from 'classnames'+import { useTranslation } from 'react-i18next'+import { useContext } from 'use-context-selector'+import { useMount } from 'ahooks'+import { Apps02 } from '@/app/components/base/icons/src/vender/line/others'+import I18n from '@/context/i18n'+import { getLanguage } from '@/i18n/language'+import { useStore as useLabelStore } from '@/app/components/tools/labels/store'+import { fetchLabelList } from '@/service/tools'++type Props = {+ value: string+ onSelect: (type: string) => void+}++const Icon = ({ svgString, active }: { svgString: string; active: boolean }) => {+ const svgRef = useRef<SVGSVGElement | null>(null)+ const SVGParsor = (svg: string) => {+ if (!svg)+ return null+ const parser = new DOMParser()+ const doc = parser.parseFromString(svg, 'image/svg+xml')+ console.log(doc.documentElement)+ return doc.documentElement+ }+ useMount(() => {+ const svgElement = SVGParsor(svgString)+ if (svgRef.current && svgElement)+ svgRef.current.appendChild(svgElement)+ })+ return <svg className={cn('w-4 h-4 text-gray-700', active && '!text-primary-600')} ref={svgRef} />+}++const Category = ({+ value,+ onSelect,+}: Props) => {+ const { t } = useTranslation()+ const { locale } = useContext(I18n)+ const language = getLanguage(locale)+ const labelList = useLabelStore(s => s.labelList)+ const setLabelList = useLabelStore(s => s.setLabelList)++ useMount(() => {+ fetchLabelList().then((res) => {+ setLabelList(res)+ })+ })++ return (+ <div className='mb-3'>+ <div className='px-3 py-0.5 text-gray-500 text-xs leading-[18px] font-medium'>{t('tools.addToolModal.category').toLocaleUpperCase()}</div>+ <div className={cn('mb-0.5 p-1 pl-3 flex items-center cursor-pointer text-gray-700 text-sm leading-5 rounded-lg hover:bg-white', value === '' && '!bg-white !text-primary-600 font-medium')} onClick={() => onSelect('')}>+ <Apps02 className='shrink-0 w-4 h-4 mr-2' />+ {t('tools.type.all')}+ </div>+ {labelList.map(label => (+ <div key={label.name} title={label.label[language]} className={cn('mb-0.5 p-1 pl-3 flex items-center cursor-pointer text-gray-700 text-sm leading-5 rounded-lg hover:bg-white truncate overflow-hidden', value === label.name && '!bg-white !text-primary-600 font-medium')} onClick={() => onSelect(label.name)}>+ <div className='shrink-0 w-4 h-4 mr-2'>+ <Icon active={value === label.name} svgString={label.icon} />+ </div>+ {label.label[language]}+ </div>+ ))}+ </div>+ )+}+export default Categorydiff --git a/web/app/components/tools/add-tool-modal/empty.png b/web/app/components/tools/add-tool-modal/empty.pngnew file mode 100644index 00000000000..da4007e45acBinary files /dev/null and b/web/app/components/tools/add-tool-modal/empty.png differdiff --git a/web/app/components/tools/add-tool-modal/empty.tsx b/web/app/components/tools/add-tool-modal/empty.tsxnew file mode 100644index 00000000000..78c2deeed44--- /dev/null+++ b/web/app/components/tools/add-tool-modal/empty.tsx@@ -0,0 +1,15 @@+import { useTranslation } from 'react-i18next'++const Empty = () => {+ const { t } = useTranslation()++ return (+ <div className='flex flex-col items-center'>+ <div className="shrink-0 w-[163px] h-[149px] bg-cover bg-no-repeat bg-[url('~@/app/components/tools/add-tool-modal/empty.png')]"></div>+ <div className='mb-1 text-[13px] font-medium text-gray-700 leading-[18px]'>{t('tools.addToolModal.emptyTitle')}</div>+ <div className='text-[13px] text-gray-500 leading-[18px]'>{t('tools.addToolModal.emptyTip')}</div>+ </div>+ )+}++export default Emptydiff --git a/web/app/components/tools/add-tool-modal/index.tsx b/web/app/components/tools/add-tool-modal/index.tsxnew file mode 100644index 00000000000..53e25fb6d8a--- /dev/null+++ b/web/app/components/tools/add-tool-modal/index.tsx@@ -0,0 +1,235 @@+'use client'+import type { FC } from 'react'+import React, { useMemo, useState } from 'react'+import { useTranslation } from 'react-i18next'+import { useContext } from 'use-context-selector'+import produce from 'immer'+import cn from 'classnames'+import { useMount } from 'ahooks'+import type { Collection, CustomCollectionBackend, Tool } from '../types'+import Type from './type'+import Category from './category'+import Tools from './tools'+import I18n from '@/context/i18n'+import { getLanguage } from '@/i18n/language'+import Drawer from '@/app/components/base/drawer'+import Button from '@/app/components/base/button'+import Loading from '@/app/components/base/loading'+import SearchInput from '@/app/components/base/search-input'+import { Plus, XClose } from '@/app/components/base/icons/src/vender/line/general'+import EditCustomToolModal from '@/app/components/tools/edit-custom-collection-modal'+import ConfigCredential from '@/app/components/tools/setting/build-in/config-credentials'+import {+ createCustomCollection,+ fetchAllBuiltInTools,+ fetchAllCustomTools,+ fetchAllWorkflowTools,+ removeBuiltInToolCredential,+ updateBuiltInToolCredential,+} from '@/service/tools'+import type { ToolWithProvider } from '@/app/components/workflow/types'+import Toast from '@/app/components/base/toast'+import ConfigContext from '@/context/debug-configuration'+import type { ModelConfig } from '@/models/debug'++type Props = {+ onHide: () => void+}+// Add and Edit+const AddToolModal: FC<Props> = ({+ onHide,+}) => {+ const { t } = useTranslation()+ const { locale } = useContext(I18n)+ const language = getLanguage(locale)+ const [currentType, setCurrentType] = useState('builtin')+ const [currentCategory, setCurrentCategory] = useState('')+ const [keywords, setKeywords] = useState<string>('')+ const handleKeywordsChange = (value: string) => {+ setKeywords(value)+ }+ const [toolList, setToolList] = useState<ToolWithProvider[]>([])+ const [listLoading, setListLoading] = useState(true)+ const getAllTools = async () => {+ setListLoading(true)+ const buildInTools = await fetchAllBuiltInTools()+ const customTools = await fetchAllCustomTools()+ const workflowTools = await fetchAllWorkflowTools()+ const mergedToolList = [+ ...buildInTools,+ ...customTools,+ ...workflowTools.filter((toolWithProvider) => {+ return !toolWithProvider.tools.some((tool) => {+ return !!tool.parameters.find(item => item.name === '__image')+ })+ }),+ ]+ setToolList(mergedToolList)+ setListLoading(false)+ }+ const filteredList = useMemo(() => {+ return toolList.filter((toolWithProvider) => {+ if (currentType === 'all')+ return true+ else+ return toolWithProvider.type === currentType+ }).filter((toolWithProvider) => {+ if (!currentCategory)+ return true+ else+ return toolWithProvider.labels.includes(currentCategory)+ }).filter((toolWithProvider) => {+ return toolWithProvider.tools.some((tool) => {+ return tool.label[language].toLowerCase().includes(keywords.toLowerCase())+ })+ })+ }, [currentType, currentCategory, toolList, keywords, language])++ const {+ modelConfig,+ setModelConfig,+ } = useContext(ConfigContext)++ const [isShowEditCollectionToolModal, setIsShowEditCustomCollectionModal] = useState(false)+ const doCreateCustomToolCollection = async (data: CustomCollectionBackend) => {+ await createCustomCollection(data)+ Toast.notify({+ type: 'success',+ message: t('common.api.actionSuccess'),+ })+ setIsShowEditCustomCollectionModal(false)+ getAllTools()+ }+ const [showSettingAuth, setShowSettingAuth] = useState(false)+ const [collection, setCollection] = useState<Collection>()+ const toolSelectHandle = (collection: Collection, tool: Tool) => {+ const parameters: Record<string, string> = {}+ if (tool.parameters) {+ tool.parameters.forEach((item) => {+ parameters[item.name] = ''+ })+ }++ const nexModelConfig = produce(modelConfig, (draft: ModelConfig) => {+ draft.agentConfig.tools.push({+ provider_id: collection.id || collection.name,+ provider_type: collection.type,+ provider_name: collection.name,+ tool_name: tool.name,+ tool_label: tool.label[locale] || tool.label[locale.replaceAll('-', '_')],+ tool_parameters: parameters,+ enabled: true,+ })+ })+ setModelConfig(nexModelConfig)+ }+ const authSelectHandle = (provider: Collection) => {+ setCollection(provider)+ setShowSettingAuth(true)+ }+ const updateBuiltinAuth = async (value: Record<string, any>) => {+ if (!collection)+ return+ await updateBuiltInToolCredential(collection.name, value)+ Toast.notify({+ type: 'success',+ message: t('common.api.actionSuccess'),+ })+ await getAllTools()+ setShowSettingAuth(false)+ }+ const removeBuiltinAuth = async () => {+ if (!collection)+ return+ await removeBuiltInToolCredential(collection.name)+ Toast.notify({+ type: 'success',+ message: t('common.api.actionSuccess'),+ })+ await getAllTools()+ setShowSettingAuth(false)+ }++ useMount(() => {+ getAllTools()+ })++ return (+ <>+ <Drawer+ isOpen+ mask+ clickOutsideNotOpen+ onClose={onHide}+ footer={null}+ panelClassname={cn('mt-16 mx-2 sm:mr-2 mb-3 !p-0 rounded-xl', 'mt-2 !w-[640px]', '!max-w-[640px]')}+ >+ <div+ className='w-full flex bg-white border-[0.5px] border-gray-200 rounded-xl shadow-xl'+ style={{+ height: 'calc(100vh - 16px)',+ }}+ >+ <div className='relative shrink-0 w-[200px] pb-3 bg-gray-100 rounded-l-xl border-r-[0.5px] border-black/2 overflow-y-auto'>+ <div className='sticky top-0 left-0 right-0'>+ <div className='sticky top-0 left-0 right-0 px-5 py-3 text-md font-semibold text-gray-900'>{t('tools.addTool')}</div>+ <div className='px-3 pt-2 pb-4'>+ <Button type='primary' className='w-[176px] text-[13px] leading-[18px] font-medium' onClick={() => setIsShowEditCustomCollectionModal(true)}>+ <Plus className='w-4 h-4 mr-1'/>+ {t('tools.createCustomTool')}+ </Button>+ </div>+ </div>+ <div className='px-2 py-1'>+ <Type value={currentType} onSelect={setCurrentType}/>+ <Category value={currentCategory} onSelect={setCurrentCategory}/>+ </div>+ </div>+ <div className='relative grow bg-white rounded-r-xl overflow-y-auto'>+ <div className='z-10 sticky top-0 left-0 right-0 p-2 flex items-center gap-1 bg-white'>+ <div className='grow'>+ <SearchInput className='w-full' value={keywords} onChange={handleKeywordsChange} />+ </div>+ <div className='ml-2 mr-1 w-[1px] h-4 bg-gray-200'></div>+ <div className='p-2 cursor-pointer' onClick={onHide}>+ <XClose className='w-4 h-4 text-gray-500' />+ </div>+ </div>+ {listLoading && (+ <div className='flex h-[200px] items-center justify-center bg-white'>+ <Loading />+ </div>+ )}+ {!listLoading && (+ <Tools+ showWorkflowEmpty={currentType === 'workflow'}+ tools={filteredList}+ addedTools={(modelConfig?.agentConfig?.tools as any) || []}+ onSelect={toolSelectHandle}+ onAuthSetup={authSelectHandle}+ />+ )}+ </div>+ </div>+ </Drawer>+ {isShowEditCollectionToolModal && (+ <EditCustomToolModal+ positionLeft+ payload={null}+ onHide={() => setIsShowEditCustomCollectionModal(false)}+ onAdd={doCreateCustomToolCollection}+ />+ )}+ {showSettingAuth && collection && (+ <ConfigCredential+ collection={collection}+ onCancel={() => setShowSettingAuth(false)}+ onSaved={updateBuiltinAuth}+ onRemove={removeBuiltinAuth}+ />+ )}+ </>++ )+}+export default React.memo(AddToolModal)diff --git a/web/app/components/tools/add-tool-modal/tools.tsx b/web/app/components/tools/add-tool-modal/tools.tsxnew file mode 100644index 00000000000..9ba5ba81a98--- /dev/null+++ b/web/app/components/tools/add-tool-modal/tools.tsx@@ -0,0 +1,146 @@+import {+ memo,+ useCallback,+} from 'react'+import cn from 'classnames'+import { useTranslation } from 'react-i18next'+import { ArrowUpRight } from '@/app/components/base/icons/src/vender/line/arrows'+import { Check, Plus } from '@/app/components/base/icons/src/vender/line/general'+import { Tag01 } from '@/app/components/base/icons/src/vender/line/financeAndECommerce'+import type { ToolWithProvider } from '@/app/components/workflow/types'+import { BlockEnum } from '@/app/components/workflow/types'+import BlockIcon from '@/app/components/workflow/block-icon'+import Tooltip from '@/app/components/base/tooltip'+import Button from '@/app/components/base/button'+import { useGetLanguage } from '@/context/i18n'+import { useStore as useLabelStore } from '@/app/components/tools/labels/store'+import Empty from '@/app/components/tools/add-tool-modal/empty'+import type { Tool } from '@/app/components/tools/types'+import { CollectionType } from '@/app/components/tools/types'+import type { AgentTool } from '@/types/app'+import { MAX_TOOLS_NUM } from '@/config'++type ToolsProps = {+ showWorkflowEmpty: boolean+ tools: ToolWithProvider[]+ addedTools: AgentTool[]+ onSelect: (provider: ToolWithProvider, tool: Tool) => void+ onAuthSetup: (provider: ToolWithProvider) => void+}+const Blocks = ({+ showWorkflowEmpty,+ tools,+ addedTools,+ onSelect,+ onAuthSetup,+}: ToolsProps) => {+ const { t } = useTranslation()+ const language = useGetLanguage()+ const labelList = useLabelStore(s => s.labelList)+ const addable = addedTools.length < MAX_TOOLS_NUM++ const renderGroup = useCallback((toolWithProvider: ToolWithProvider) => {+ const list = toolWithProvider.tools+ const needAuth = toolWithProvider.allow_delete && !toolWithProvider.is_team_authorization && toolWithProvider.type === CollectionType.builtIn++ return (+ <div+ key={toolWithProvider.id}+ className='group mb-1 last-of-type:mb-0'+ >+ <div className='flex items-center justify-between w-full pl-3 pr-1 h-[22px] text-xs font-medium text-gray-500'>+ {toolWithProvider.label[language]}+ <a className='hidden cursor-pointer items-center group-hover:flex' href={`/tools?category=${toolWithProvider.type}`} target='_blank'>{t('tools.addToolModal.manageInTools')}<ArrowUpRight className='ml-0.5 w-3 h-3' /></a>+ </div>+ {list.map((tool) => {+ const labelContent = (() => {+ if (!tool.labels)+ return ''+ return tool.labels.map((name) => {+ const label = labelList.find(item => item.name === name)+ return label?.label[language]+ }).filter(Boolean).join(', ')+ })()+ const added = !!addedTools?.find(v => v.provider_id === toolWithProvider.id && v.provider_type === toolWithProvider.type && v.tool_name === tool.name)+ return (+ <Tooltip+ key={tool.name}+ selector={`workflow-block-tool-${tool.name}`}+ position='bottom'+ className='!p-0 !px-3 !py-2.5 !w-[210px] !leading-[18px] !text-xs !text-gray-700 !border-[0.5px] !border-black/5 !bg-transparent !rounded-xl !shadow-lg translate-x-[108px]'+ htmlContent={(+ <div>+ <BlockIcon+ size='md'+ className='mb-2'+ type={BlockEnum.Tool}+ toolIcon={toolWithProvider.icon}+ />+ <div className='mb-1 text-sm leading-5 text-gray-900'>{tool.label[language]}</div>+ <div className='text-xs text-gray-700 leading-[18px]'>{tool.description[language]}</div>+ {tool.labels?.length > 0 && (+ <div className='flex items-center shrink-0 mt-1'>+ <div className='relative w-full flex items-center gap-1 py-1 rounded-md text-gray-500' title={labelContent}>+ <Tag01 className='shrink-0 w-3 h-3 text-gray-500' />+ <div className='grow text-xs text-start leading-[18px] font-normal truncate'>{labelContent}</div>+ </div>+ </div>+ )}+ </div>+ )}+ noArrow+ >+ <div className='group/item flex items-center w-full pl-3 pr-1 h-8 rounded-lg hover:bg-gray-50 cursor-pointer'>+ <BlockIcon+ className={cn('mr-2 shrink-0', needAuth && 'opacity-30')}+ type={BlockEnum.Tool}+ toolIcon={toolWithProvider.icon}+ />+ <div className={cn('grow text-sm text-gray-900 truncate', needAuth && 'opacity-30')}>{tool.label[language]}</div>+ {!needAuth && added && (+ <div className='flex items-center gap-1 rounded-[6px] border border-gray-100 px-2 py-[3px] bg-white text-gray-300 text-xs font-medium leading-[18px]'>+ <Check className='w-3 h-3'/>+ {t('tools.addToolModal.added').toLocaleUpperCase()}+ </div>+ )}+ {!needAuth && !added && addable && (+ <Button+ type='default'+ className={cn('hidden shrink-0 items-center !h-6 px-2 py-1 bg-white text-xs font-medium leading-[18px] text-primary-600 group-hover/item:flex')}+ onClick={() => onSelect(toolWithProvider, tool)}+ >+ <Plus className='w-3 h-3'/>+ {t('tools.addToolModal.add').toLocaleUpperCase()}+ </Button>+ )}+ {needAuth && (+ <Button+ type='default'+ className={cn('hidden shrink-0 items-center !h-6 px-2 py-1 bg-white text-xs font-medium leading-[18px] text-primary-600 group-hover/item:flex')}+ onClick={() => onAuthSetup(toolWithProvider)}+ >{t('tools.auth.setup')}</Button>+ )}+ </div>+ </Tooltip>+ )+ })}+ </div>+ )+ }, [addable, language, t, labelList, addedTools, onAuthSetup, onSelect])++ return (+ <div className='p-1 pb-6 max-w-[440px]'>+ {!tools.length && !showWorkflowEmpty && (+ <div className='flex items-center px-3 h-[22px] text-xs font-medium text-gray-500'>{t('workflow.tabs.noResult')}</div>+ )}+ {!tools.length && showWorkflowEmpty && (+ <div className='pt-[280px]'>+ <Empty/>+ </div>+ )}+ {!!tools.length && tools.map(renderGroup)}+ </div>+ )+}++export default memo(Blocks)diff --git a/web/app/components/tools/add-tool-modal/type.tsx b/web/app/components/tools/add-tool-modal/type.tsxnew file mode 100644index 00000000000..74e5e730962--- /dev/null+++ b/web/app/components/tools/add-tool-modal/type.tsx@@ -0,0 +1,34 @@+'use client'+import cn from 'classnames'+import { useTranslation } from 'react-i18next'+import { Exchange02, FileCode } from '@/app/components/base/icons/src/vender/line/others'++type Props = {+ value: string+ onSelect: (type: string) => void+}++const Types = ({+ value,+ onSelect,+}: Props) => {+ const { t } = useTranslation()++ return (+ <div className='mb-3'>+ <div className={cn('mb-0.5 p-1 pl-3 flex items-center cursor-pointer text-sm leading-5 rounded-lg hover:bg-white', value === 'builtin' && '!bg-white font-medium')} onClick={() => onSelect('builtin')}>+ <div className="shrink-0 w-4 h-4 mr-2 bg-cover bg-no-repeat bg-[url('~@/app/components/tools/add-tool-modal/D.png')]" />+ <span className={cn('text-gray-700', value === 'builtin' && '!text-primary-600')}>{t('tools.type.builtIn')}</span>+ </div>+ <div className={cn('mb-0.5 p-1 pl-3 flex items-center cursor-pointer text-gray-700 text-sm leading-5 rounded-lg hover:bg-white', value === 'api' && '!bg-white !text-primary-600 font-medium')} onClick={() => onSelect('api')}>+ <FileCode className='shrink-0 w-4 h-4 mr-2' />+ {t('tools.type.custom')}+ </div>+ <div className={cn('mb-0.5 p-1 pl-3 flex items-center cursor-pointer text-gray-700 text-sm leading-5 rounded-lg hover:bg-white', value === 'workflow' && '!bg-white !text-primary-600 font-medium')} onClick={() => onSelect('workflow')}>+ <Exchange02 className='shrink-0 w-4 h-4 mr-2' />+ {t('tools.type.workflow')}+ </div>+ </div>+ )+}+export default Typesdiff --git a/web/app/components/tools/contribute.tsx b/web/app/components/tools/contribute.tsxdeleted file mode 100644index aeec959614f..00000000000--- a/web/app/components/tools/contribute.tsx+++ /dev/null@@ -1,31 +0,0 @@-'use client'-import type { FC } from 'react'-import React from 'react'-import { useTranslation } from 'react-i18next'-import { Heart02 } from '../base/icons/src/vender/solid/education'-import { BookOpen01 } from '../base/icons/src/vender/line/education'--const Contribute: FC = () => {- const { t } = useTranslation()-- return (- <div className='shrink-0 p-2'>- <div className='inline-block p-2 bg-white shadow-lg rounded-lg'>- <Heart02 className='w-3 h-3 text-[#EE46BC]' />- </div>- <div className='mt-2'>- <div className='text-gradient'>- {t('tools.contribute.line1')}- </div>- <div className='text-gradient'>- {t('tools.contribute.line2')}- </div>- </div>- <a href='https://github.com/langgenius/dify/blob/main/CONTRIBUTING.md' target='_blank' rel='noopener noreferrer' className='mt-1 flex items-center space-x-1 text-[#155EEF]'>- <BookOpen01 className='w-3 h-3' />- <div className='leading-[18px] text-xs font-normal'>{t('tools.contribute.viewGuide')}</div>- </a>- </div>- )-}-export default React.memo(Contribute)diff --git a/web/app/components/tools/edit-custom-collection-modal/config-credentials.tsx b/web/app/components/tools/edit-custom-collection-modal/config-credentials.tsxindex 9da0ff7dccf..cdff5424313 100644--- a/web/app/components/tools/edit-custom-collection-modal/config-credentials.tsx+++ b/web/app/components/tools/edit-custom-collection-modal/config-credentials.tsx@@ -12,6 +12,7 @@ import Radio from '@/app/components/base/radio/ui'import { AuthHeaderPrefix, AuthType } from '@/app/components/tools/types'type Props = {+ positionCenter?: booleancredential: CredentialonChange: (credential: Credential) => voidonHide: () => void@@ -38,6 +39,7 @@ const SelectItem: FC<ItemProps> = ({ text, value, isChecked, onClick }) => {}const ConfigCredential: FC<Props> = ({+ positionCenter,credential,onChange,onHide,@@ -48,6 +50,7 @@ const ConfigCredential: FC<Props> = ({return (<DrawerisShow+ positionCenter={positionCenter}onHide={onHide}title={t('tools.createTool.authMethod.title')!}panelClassName='mt-2 !w-[520px]'diff --git a/web/app/components/tools/edit-custom-collection-modal/index.tsx b/web/app/components/tools/edit-custom-collection-modal/index.tsxindex 9d5e815874c..ba704279294 100644--- a/web/app/components/tools/edit-custom-collection-modal/index.tsx+++ b/web/app/components/tools/edit-custom-collection-modal/index.tsx@@ -16,9 +16,11 @@ import Button from '@/app/components/base/button'import EmojiPicker from '@/app/components/base/emoji-picker'import AppIcon from '@/app/components/base/app-icon'import { parseParamsSchema } from '@/service/tools'+import LabelSelector from '@/app/components/tools/labels/selector'const fieldNameClassNames = 'py-2 leading-5 text-sm font-medium text-gray-900'type Props = {+ positionLeft?: booleanpayload: anyonHide: () => voidonAdd?: (payload: CustomCollectionBackend) => void@@ -27,6 +29,7 @@ type Props = {}// Add and Editconst EditCustomCollectionModal: FC<Props> = ({+ positionLeft,payload,onHide,onAdd,@@ -114,6 +117,11 @@ const EditCustomCollectionModal: FC<Props> = ({const [currTool, setCurrTool] = useState<CustomParamSchema | null>(null)const [isShowTestApi, setIsShowTestApi] = useState(false)+ const [labels, setLabels] = useState<string[]>(payload?.labels || [])+ const handleLabelSelect = (value: string[]) => {+ setLabels(value)+ }+const handleSave = () => {// const postData = clone(customCollection)const postData = produce(customCollection, (draft) => {@@ -124,6 +132,8 @@ const EditCustomCollectionModal: FC<Props> = ({delete draft.credentials.api_key_header_prefixdelete draft.credentials.api_key_value}++ draft.labels = labels})if (isAdd) {@@ -154,10 +164,11 @@ const EditCustomCollectionModal: FC<Props> = ({<><DrawerisShow+ positionCenter={isAdd && !positionLeft}onHide={onHide}title={t(`tools.createTool.${isAdd ? 'title' : 'editTitle'}`)!}- panelClassName='mt-2 !w-[640px]'- maxWidthClassName='!max-w-[640px]'+ panelClassName='mt-2 !w-[630px]'+ maxWidthClassName='!max-w-[630px]'height='calc(100vh - 16px)'headerClassName='!border-b-black/5'body={@@ -254,6 +265,13 @@ const EditCustomCollectionModal: FC<Props> = ({</div></div>+ {/* Labels */}+ <div>+ <div className='py-2 leading-5 text-sm font-medium text-gray-900'>{t('tools.createTool.toolInput.label')}</div>+ <LabelSelector value={labels} onChange={handleLabelSelect} />+ </div>++ {/* Privacy Policy */}<div><div className={fieldNameClassNames}>{t('tools.createTool.privacyPolicy')}</div><input@@ -288,7 +306,7 @@ const EditCustomCollectionModal: FC<Props> = ({)}<div className='flex space-x-2 '>- <Button className='flex items-center h-8 !px-3 !text-[13px] font-medium !text-gray-700' onClick={onHide}>{t('common.operation.cancel')}</Button>+ <Button className='flex items-center h-8 !px-3 !text-[13px] font-medium !text-gray-700 bg-white' onClick={onHide}>{t('common.operation.cancel')}</Button><Button className='flex items-center h-8 !px-3 !text-[13px] font-medium' type='primary' onClick={handleSave}>{t('common.operation.save')}</Button></div></div>@@ -308,6 +326,7 @@ const EditCustomCollectionModal: FC<Props> = ({/>}{credentialsModalShow && (<ConfigCredentials+ positionCenter={isAdd}credential={credential}onChange={setCredential}onHide={() => setCredentialsModalShow(false)}@@ -315,6 +334,7 @@ const EditCustomCollectionModal: FC<Props> = ({}{isShowTestApi && (<TestApi+ positionCenter={isAdd}tool={currTool as CustomParamSchema}customCollection={customCollection}onHide={() => setIsShowTestApi(false)}diff --git a/web/app/components/tools/edit-custom-collection-modal/test-api.tsx b/web/app/components/tools/edit-custom-collection-modal/test-api.tsxindex 791ac5edbff..793589800a8 100644--- a/web/app/components/tools/edit-custom-collection-modal/test-api.tsx+++ b/web/app/components/tools/edit-custom-collection-modal/test-api.tsx@@ -13,6 +13,7 @@ import { testAPIAvailable } from '@/service/tools'import { getLanguage } from '@/i18n/language'type Props = {+ positionCenter?: booleancustomCollection: CustomCollectionBackendtool: CustomParamSchemaonHide: () => void@@ -21,6 +22,7 @@ type Props = {const keyClassNames = 'py-2 leading-5 text-sm font-medium text-gray-900'const TestApi: FC<Props> = ({+ positionCenter,customCollection,tool,onHide,@@ -57,6 +59,7 @@ const TestApi: FC<Props> = ({<><DrawerisShow+ positionCenter={positionCenter}onHide={onHide}title={`${t('tools.test.title')} ${toolName}`}panelClassName='mt-2 !w-[600px]'@@ -119,6 +122,7 @@ const TestApi: FC<Props> = ({/>{credentialsModalShow && (<ConfigCredentials+ positionCenter={positionCenter}credential={tempCredential}onChange={setTempCredential}onHide={() => setCredentialsModalShow(false)}diff --git a/web/app/components/tools/index.tsx b/web/app/components/tools/index.tsxdeleted file mode 100644index b467dcbad50..00000000000--- a/web/app/components/tools/index.tsx+++ /dev/null@@ -1,259 +0,0 @@-'use client'-import type { FC } from 'react'-import React, { useEffect, useState } from 'react'-import { useTranslation } from 'react-i18next'-import cn from 'classnames'-import Button from '../base/button'-import { Plus } from '../base/icons/src/vender/line/general'-import Toast from '../base/toast'-import type { Collection, CustomCollectionBackend, Tool } from './types'-import { CollectionType, LOC } from './types'-import ToolNavList from './tool-nav-list'-import Search from './search'-import Contribute from './contribute'-import ToolList from './tool-list'-import EditCustomToolModal from './edit-custom-collection-modal'-import NoCustomTool from './info/no-custom-tool'-import NoSearchRes from './info/no-search-res'-import NoCustomToolPlaceholder from './no-custom-tool-placeholder'-import { useTabSearchParams } from '@/hooks/use-tab-searchparams'-import TabSlider from '@/app/components/base/tab-slider'-import { createCustomCollection, fetchCollectionList as doFetchCollectionList, fetchBuiltInToolList, fetchCustomToolList, fetchModelToolList } from '@/service/tools'-import type { AgentTool } from '@/types/app'--type Props = {- loc: LOC- addedTools?: AgentTool[]- onAddTool?: (collection: Collection, payload: Tool) => void- selectedProviderId?: string-}--const Tools: FC<Props> = ({- loc,- addedTools,- onAddTool,- selectedProviderId,-}) => {- const { t } = useTranslation()- const isInToolsPage = loc === LOC.tools- const isInDebugPage = !isInToolsPage-- const [collectionList, setCollectionList] = useState<Collection[]>([])- const [currCollectionIndex, setCurrCollectionIndex] = useState<number | null>(null)-- const [isDetailLoading, setIsDetailLoading] = useState(false)-- const fetchCollectionList = async () => {- const list = await doFetchCollectionList()- setCollectionList(list)- if (list.length > 0 && currCollectionIndex === null) {- let index = 0- if (selectedProviderId)- index = list.findIndex(item => item.id === selectedProviderId)-- setCurrCollectionIndex(index || 0)- }- }- useEffect(() => {- fetchCollectionList()- }, [])-- const collectionTypeOptions = (() => {- const res = [- { value: CollectionType.builtIn, text: t('tools.type.builtIn') },- { value: CollectionType.custom, text: t('tools.type.custom') },- ]- if (!isInToolsPage)- res.unshift({ value: CollectionType.all, text: t('tools.type.all') })- return res- })()-- const [query, setQuery] = useState('')- const [toolPageCollectionType, setToolPageCollectionType] = useTabSearchParams({- defaultTab: collectionTypeOptions[0].value,- })- const [appPageCollectionType, setAppPageCollectionType] = useState(collectionTypeOptions[0].value)- const { collectionType, setCollectionType } = (() => {- if (isInToolsPage) {- return {- collectionType: toolPageCollectionType,- setCollectionType: setToolPageCollectionType,- }- }- return {- collectionType: appPageCollectionType,- setCollectionType: setAppPageCollectionType,- }- })()-- const showCollectionList = (() => {- let typeFilteredList: Collection[] = []- if (collectionType === CollectionType.all)- typeFilteredList = collectionList.filter(item => item.type !== CollectionType.model)- else if (collectionType === CollectionType.builtIn)- typeFilteredList = collectionList.filter(item => item.type === CollectionType.builtIn)- else if (collectionType === CollectionType.custom)- typeFilteredList = collectionList.filter(item => item.type === CollectionType.custom)- if (query)- return typeFilteredList.filter(item => item.name.includes(query))-- return typeFilteredList- })()-- const hasNoCustomCollection = !collectionList.find(item => item.type === CollectionType.custom)-- useEffect(() => {- setCurrCollectionIndex(0)- }, [collectionType])-- const currCollection = (() => {- if (currCollectionIndex === null)- return null- return showCollectionList[currCollectionIndex]- })()-- const [currTools, setCurrentTools] = useState<Tool[]>([])- useEffect(() => {- if (!currCollection)- return-- (async () => {- setIsDetailLoading(true)- try {- if (currCollection.type === CollectionType.builtIn) {- const list = await fetchBuiltInToolList(currCollection.name)- setCurrentTools(list)- }- else if (currCollection.type === CollectionType.model) {- const list = await fetchModelToolList(currCollection.name)- setCurrentTools(list)- }- else {- const list = await fetchCustomToolList(currCollection.name)- setCurrentTools(list)- }- }- catch (e) { }- setIsDetailLoading(false)- })()- }, [currCollection?.name, currCollection?.type])-- const [isShowEditCollectionToolModal, setIsShowEditCollectionToolModal] = useState(false)- const handleCreateToolCollection = () => {- setIsShowEditCollectionToolModal(true)- }-- const doCreateCustomToolCollection = async (data: CustomCollectionBackend) => {- await createCustomCollection(data)- Toast.notify({- type: 'success',- message: t('common.api.actionSuccess'),- })- await fetchCollectionList()- setIsShowEditCollectionToolModal(false)- }-- return (- <>- <div className='flex h-full'>- {/* sidebar */}- <div className={cn(isInToolsPage ? 'sm:w-[216px] px-4' : 'sm:w-[256px] px-3', 'flex flex-col w-16 shrink-0 pb-2')}>- {isInToolsPage && (- <Button className='mt-6 flex items-center !h-8 pl-4' type='primary' onClick={handleCreateToolCollection}>- <Plus className='w-4 h-4 mr-1' />- <div className='leading-[18px] text-[13px] font-medium truncate'>{t('tools.createCustomTool')}</div>- </Button>- )}-- {isInDebugPage && (- <div className='mt-6 flex space-x-1 items-center'>- <Search- className='grow'- value={query}- onChange={setQuery}- />- <Button className='flex items-center justify-center !w-8 !h-8 !p-0' type='primary'>- <Plus className='w-4 h-4' onClick={handleCreateToolCollection} />- </Button>- </div>- )}-- <TabSlider- className='mt-3'- itemWidth={isInToolsPage ? 89 : 75}- value={collectionType}- onChange={v => setCollectionType(v as CollectionType)}- options={collectionTypeOptions}- />- {isInToolsPage && (- <Search- className='mt-5'- value={query}- onChange={setQuery}- />- )}-- {(collectionType === CollectionType.custom && hasNoCustomCollection)- ? (- <div className='grow h-0 p-2 pt-8'>- <NoCustomTool onCreateTool={handleCreateToolCollection} />- </div>- )- : (- (showCollectionList.length > 0 || !query)- ? <ToolNavList- className='mt-2 grow height-0 overflow-y-auto'- currentIndex={currCollectionIndex || 0}- list={showCollectionList}- onChosen={setCurrCollectionIndex}- />- : (- <div className='grow h-0 p-2 pt-8'>- <NoSearchRes- onReset={() => { setQuery('') }}- />- </div>- )- )}-- {loc === LOC.tools && (- <Contribute />- )}- </div>-- {/* tools */}- <div className={cn('grow h-full overflow-hidden p-2')}>- <div className='h-full bg-white rounded-2xl'>- {!(collectionType === CollectionType.custom && hasNoCustomCollection) && showCollectionList.length > 0 && (- <ToolList- collection={currCollection}- list={currTools}- loc={loc}- addedTools={addedTools}- onAddTool={onAddTool}- onRefreshData={fetchCollectionList}- onCollectionRemoved={() => {- setCurrCollectionIndex(0)- fetchCollectionList()- }}- isLoading={isDetailLoading}- />- )}-- {collectionType === CollectionType.custom && hasNoCustomCollection && (- <NoCustomToolPlaceholder />- )}- </div>- </div>- </div>- {isShowEditCollectionToolModal && (- <EditCustomToolModal- payload={null}- onHide={() => setIsShowEditCollectionToolModal(false)}- onAdd={doCreateCustomToolCollection}- />- )}- </>- )-}-export default React.memo(Tools)diff --git a/web/app/components/tools/info/no-custom-tool.tsx b/web/app/components/tools/info/no-custom-tool.tsxdeleted file mode 100644index 91c09253c1c..00000000000--- a/web/app/components/tools/info/no-custom-tool.tsx+++ /dev/null@@ -1,38 +0,0 @@-'use client'-import type { FC } from 'react'-import React from 'react'-import { useTranslation } from 'react-i18next'-import { Icon3Dots } from '../../base/icons/src/public/other'-import { Tools } from '@/app/components/base/icons/src/public/header-nav/tools'-type Props = {- onCreateTool: () => void-}--const NoCustomTool: FC<Props> = ({- onCreateTool,-}) => {- const { t } = useTranslation()-- return (- <div>- <div className='inline-flex p-3 rounded-lg bg-gray-50 border border-[#EAECF5]'>- <Tools className='w-5 h-5 text-gray-500' />- </div>- <div className='mt-2'>- <div className='leading-5 text-sm font-medium text-gray-500'>- {t('tools.noCustomTool.title')}<Icon3Dots className='inline relative -top-3 -left-1.5' />- </div>- <div className='mt-1 leading-[18px] text-xs font-normal text-gray-500'>- {t('tools.noCustomTool.content')}- </div>- <div- className='mt-2 leading-[18px] text-xs font-medium text-[#155EEF] uppercase cursor-pointer'- onClick={onCreateTool}- >- {t('tools.noCustomTool.createTool')}- </div>- </div>- </div>- )-}-export default React.memo(NoCustomTool)diff --git a/web/app/components/tools/info/no-search-res.tsx b/web/app/components/tools/info/no-search-res.tsxdeleted file mode 100644index f4752ab1846..00000000000--- a/web/app/components/tools/info/no-search-res.tsx+++ /dev/null@@ -1,38 +0,0 @@-'use client'-import type { FC } from 'react'-import React from 'react'-import { useTranslation } from 'react-i18next'-import { SearchMd } from '../../base/icons/src/vender/solid/general'--type Props = {- onReset: () => void-}--const NoSearchRes: FC<Props> = ({- onReset,-}) => {- const { t } = useTranslation()-- return (- <div>- <div className='inline-flex p-3 rounded-lg bg-gray-50 border border-[#EAECF5]'>- <SearchMd className='w-5 h-5 text-gray-500' />- </div>- <div className='mt-2'>- <div className='leading-5 text-sm font-medium text-gray-500'>- {t('tools.noSearchRes.title')}- </div>- <div className='mt-1 leading-[18px] text-xs font-normal text-gray-500'>- {t('tools.noSearchRes.content')}- </div>- <div- className='mt-2 leading-[18px] text-xs font-medium text-[#155EEF] uppercase cursor-pointer'- onClick={onReset}- >- {t('tools.noSearchRes.reset')}- </div>- </div>- </div>- )-}-export default React.memo(NoSearchRes)diff --git a/web/app/components/tools/labels/constant.ts b/web/app/components/tools/labels/constant.tsnew file mode 100644index 00000000000..3f073859d93--- /dev/null+++ b/web/app/components/tools/labels/constant.ts@@ -0,0 +1,6 @@+import type { TypeWithI18N } from '@/app/components/header/account-setting/model-provider-page/declarations'+export type Label = {+ name: string+ icon: string+ label: TypeWithI18N+}diff --git a/web/app/components/tools/labels/filter.tsx b/web/app/components/tools/labels/filter.tsxnew file mode 100644index 00000000000..23c2b46524d--- /dev/null+++ b/web/app/components/tools/labels/filter.tsx@@ -0,0 +1,144 @@+import type { FC } from 'react'+import { useMemo, useState } from 'react'+import { useTranslation } from 'react-i18next'+import { useContext } from 'use-context-selector'+import { useDebounceFn, useMount } from 'ahooks'+import cn from 'classnames'+import { useStore as useLabelStore } from './store'+import {+ PortalToFollowElem,+ PortalToFollowElemContent,+ PortalToFollowElemTrigger,+} from '@/app/components/base/portal-to-follow-elem'+import SearchInput from '@/app/components/base/search-input'+import { ChevronDown } from '@/app/components/base/icons/src/vender/line/arrows'+import { Tag01, Tag03 } from '@/app/components/base/icons/src/vender/line/financeAndECommerce'+import { Check } from '@/app/components/base/icons/src/vender/line/general'+import { XCircle } from '@/app/components/base/icons/src/vender/solid/general'+import type { Label } from '@/app/components/tools/labels/constant'+import { fetchLabelList } from '@/service/tools'+import I18n from '@/context/i18n'+import { getLanguage } from '@/i18n/language'++type LabelFilterProps = {+ value: string[]+ onChange: (v: string[]) => void+}+const LabelFilter: FC<LabelFilterProps> = ({+ value,+ onChange,+}) => {+ const { t } = useTranslation()+ const { locale } = useContext(I18n)+ const language = getLanguage(locale)+ const [open, setOpen] = useState(false)++ const labelList = useLabelStore(s => s.labelList)+ const setLabelList = useLabelStore(s => s.setLabelList)++ const [keywords, setKeywords] = useState('')+ const [searchKeywords, setSearchKeywords] = useState('')+ const { run: handleSearch } = useDebounceFn(() => {+ setSearchKeywords(keywords)+ }, { wait: 500 })+ const handleKeywordsChange = (value: string) => {+ setKeywords(value)+ handleSearch()+ }++ const filteredLabelList = useMemo(() => {+ return labelList.filter(label => label.name.includes(searchKeywords))+ }, [labelList, searchKeywords])++ const currentLabel = useMemo(() => {+ return labelList.find(label => label.name === value[0])+ }, [value, labelList])++ const selectLabel = (label: Label) => {+ if (value.includes(label.name))+ onChange(value.filter(v => v !== label.name))+ else+ onChange([...value, label.name])+ }++ useMount(() => {+ fetchLabelList().then((res) => {+ setLabelList(res)+ })+ })++ return (+ <PortalToFollowElem+ open={open}+ onOpenChange={setOpen}+ placement='bottom-start'+ offset={4}+ >+ <div className='relative'>+ <PortalToFollowElemTrigger+ onClick={() => setOpen(v => !v)}+ className='block'+ >+ <div className={cn(+ 'flex items-center gap-1 px-2 h-8 rounded-lg border-[0.5px] border-transparent bg-gray-200 cursor-pointer hover:bg-gray-300',+ open && !value.length && '!bg-gray-300 hover:bg-gray-300',+ !open && !!value.length && '!bg-white/80 shadow-xs !border-black/5 hover:!bg-gray-200',+ open && !!value.length && '!bg-gray-200 !border-black/5 shadow-xs hover:!bg-gray-200',+ )}>+ <div className='p-[1px]'>+ <Tag01 className='h-3.5 w-3.5 text-gray-700' />+ </div>+ <div className='text-[13px] leading-[18px] text-gray-700'>+ {!value.length && t('common.tag.placeholder')}+ {!!value.length && currentLabel?.label[language]}+ </div>+ {value.length > 1 && (+ <div className='text-xs font-medium leading-[18px] text-gray-500'>{`+${value.length - 1}`}</div>+ )}+ {!value.length && (+ <div className='p-[1px]'>+ <ChevronDown className='h-3.5 w-3.5 text-gray-700'/>+ </div>+ )}+ {!!value.length && (+ <div className='p-[1px] cursor-pointer group/clear' onClick={(e) => {+ e.stopPropagation()+ onChange([])+ }}>+ <XCircle className='h-3.5 w-3.5 text-gray-400 group-hover/clear:text-gray-600'/>+ </div>+ )}+ </div>+ </PortalToFollowElemTrigger>+ <PortalToFollowElemContent className='z-[1002]'>+ <div className='relative w-[240px] bg-white rounded-lg border-[0.5px] border-gray-200 shadow-lg'>+ <div className='p-2 border-b-[0.5px] border-black/5'>+ <SearchInput white value={keywords} onChange={handleKeywordsChange} />+ </div>+ <div className='p-1'>+ {filteredLabelList.map(label => (+ <div+ key={label.name}+ className='flex items-center gap-2 pl-3 py-[6px] pr-2 rounded-lg cursor-pointer hover:bg-gray-100'+ onClick={() => selectLabel(label)}+ >+ <div title={label.label[language]} className='grow text-sm text-gray-700 leading-5 truncate'>{label.label[language]}</div>+ {value.includes(label.name) && <Check className='shrink-0 w-4 h-4 text-primary-600'/>}+ </div>+ ))}+ {!filteredLabelList.length && (+ <div className='p-3 flex flex-col items-center gap-1'>+ <Tag03 className='h-6 w-6 text-gray-300' />+ <div className='text-gray-500 text-xs leading-[14px]'>{t('common.tag.noTag')}</div>+ </div>+ )}+ </div>+ </div>+ </PortalToFollowElemContent>+ </div>+ </PortalToFollowElem>++ )+}++export default LabelFilterdiff --git a/web/app/components/tools/labels/selector.tsx b/web/app/components/tools/labels/selector.tsxnew file mode 100644index 00000000000..958981ba17b--- /dev/null+++ b/web/app/components/tools/labels/selector.tsx@@ -0,0 +1,128 @@+import type { FC } from 'react'+import { useMemo, useState } from 'react'+import { useTranslation } from 'react-i18next'+import { useContext } from 'use-context-selector'+import { useDebounceFn, useMount } from 'ahooks'+import cn from 'classnames'+import { useStore as useLabelStore } from './store'+import {+ PortalToFollowElem,+ PortalToFollowElemContent,+ PortalToFollowElemTrigger,+} from '@/app/components/base/portal-to-follow-elem'+import SearchInput from '@/app/components/base/search-input'+import { ChevronDown } from '@/app/components/base/icons/src/vender/line/arrows'+import { Tag03 } from '@/app/components/base/icons/src/vender/line/financeAndECommerce'+import Checkbox from '@/app/components/base/checkbox'+import type { Label } from '@/app/components/tools/labels/constant'+import { fetchLabelList } from '@/service/tools'+import I18n from '@/context/i18n'+import { getLanguage } from '@/i18n/language'++type LabelSelectorProps = {+ value: string[]+ onChange: (v: string[]) => void+}+const LabelSelector: FC<LabelSelectorProps> = ({+ value,+ onChange,+}) => {+ const { t } = useTranslation()+ const { locale } = useContext(I18n)+ const language = getLanguage(locale)+ const [open, setOpen] = useState(false)++ const labelList = useLabelStore(s => s.labelList)+ const setLabelList = useLabelStore(s => s.setLabelList)++ const [keywords, setKeywords] = useState('')+ const [searchKeywords, setSearchKeywords] = useState('')+ const { run: handleSearch } = useDebounceFn(() => {+ setSearchKeywords(keywords)+ }, { wait: 500 })+ const handleKeywordsChange = (value: string) => {+ setKeywords(value)+ handleSearch()+ }++ const filteredLabelList = useMemo(() => {+ return labelList.filter(label => label.name.includes(searchKeywords))+ }, [labelList, searchKeywords])++ const selectedLabels = useMemo(() => {+ return value.map(v => labelList.find(l => l.name === v)?.label[language]).join(', ')+ }, [value, labelList, language])++ const selectLabel = (label: Label) => {+ if (value.includes(label.name))+ onChange(value.filter(v => v !== label.name))+ else+ onChange([...value, label.name])+ }++ useMount(() => {+ fetchLabelList().then((res) => {+ setLabelList(res)+ })+ })++ return (+ <PortalToFollowElem+ open={open}+ onOpenChange={setOpen}+ placement='bottom-start'+ offset={4}+ >+ <div className='relative'>+ <PortalToFollowElemTrigger+ onClick={() => setOpen(v => !v)}+ className='block'+ >+ <div className={cn(+ 'flex items-center gap-1 px-3 h-9 rounded-lg border-[0.5px] border-transparent bg-gray-100 cursor-pointer hover:bg-gray-200',+ open && '!bg-gray-200 hover:bg-gray-200',+ )}>+ <div title={value.length > 0 ? selectedLabels : ''} className={cn('grow text-[13px] leading-[18px] text-gray-700 truncate', !value.length && '!text-gray-400')}>+ {!value.length && t('tools.createTool.toolInput.labelPlaceholder')}+ {!!value.length && selectedLabels}+ </div>+ <div className='shrink-0 ml-1 text-gray-700 opacity-60'>+ <ChevronDown className='h-4 w-4'/>+ </div>+ </div>+ </PortalToFollowElemTrigger>+ <PortalToFollowElemContent className='z-[1040]'>+ <div className='relative w-[591px] bg-white rounded-lg border-[0.5px] border-gray-200 shadow-lg'>+ <div className='p-2 border-b-[0.5px] border-black/5'>+ <SearchInput white value={keywords} onChange={handleKeywordsChange} />+ </div>+ <div className='p-1 max-h-[264px] overflow-y-auto'>+ {filteredLabelList.map(label => (+ <div+ key={label.name}+ className='flex items-center gap-2 pl-3 py-[6px] pr-2 rounded-lg cursor-pointer hover:bg-gray-100'+ onClick={() => selectLabel(label)}+ >+ <Checkbox+ className='shrink-0'+ checked={value.includes(label.name)}+ onCheck={() => {}}+ />+ <div title={label.label[language]} className='grow text-sm text-gray-700 leading-5 truncate'>{label.label[language]}</div>+ </div>+ ))}+ {!filteredLabelList.length && (+ <div className='p-3 flex flex-col items-center gap-1'>+ <Tag03 className='h-6 w-6 text-gray-300' />+ <div className='text-gray-500 text-xs leading-[14px]'>{t('common.tag.noTag')}</div>+ </div>+ )}+ </div>+ </div>+ </PortalToFollowElemContent>+ </div>+ </PortalToFollowElem>+ )+}++export default LabelSelectordiff --git a/web/app/components/tools/labels/store.ts b/web/app/components/tools/labels/store.tsnew file mode 100644index 00000000000..c19991dfd4e--- /dev/null+++ b/web/app/components/tools/labels/store.ts@@ -0,0 +1,15 @@+import { create } from 'zustand'+import type { Label } from './constant'++type State = {+ labelList: Label[]+}++type Action = {+ setLabelList: (labelList?: Label[]) => void+}++export const useStore = create<State & Action>(set => ({+ labelList: [],+ setLabelList: labelList => set(() => ({ labelList })),+}))diff --git a/web/app/components/tools/no-custom-tool-placeholder.tsx b/web/app/components/tools/no-custom-tool-placeholder.tsxdeleted file mode 100644index 7fda72140ce..00000000000--- a/web/app/components/tools/no-custom-tool-placeholder.tsx+++ /dev/null@@ -1,26 +0,0 @@-'use client'-import type { FC } from 'react'-import React from 'react'-import { useTranslation } from 'react-i18next'-import { BookOpen01 } from '../base/icons/src/vender/line/education'-import { Icon3Dots } from '../base/icons/src/public/other'--const NoCustomToolPlaceHolder: FC = () => {- const { t } = useTranslation()-- return (- <div className='h-full flex items-center justify-center'>- <div className='p-6 rounded-xl bg-gray-50'>- <div className='inline-flex p-2 border border-gray-200 rounded-md'>- <BookOpen01 className='w-4 h-4 text-primary-600' />- </div>- <div className='mt-3 leading-6 text-base font-medium text-gray-700'>- {t('tools.noCustomTool.title')}- <Icon3Dots className='inline relative -top-3 -left-1.5' />- </div>- <div className='mt-2 leading-5 text-sm font-normal text-gray-700'>{t('tools.noCustomTool.content')}</div>- </div>- </div>- )-}-export default React.memo(NoCustomToolPlaceHolder)diff --git a/web/app/components/tools/provider-list.tsx b/web/app/components/tools/provider-list.tsxnew file mode 100644index 00000000000..a888edadf25--- /dev/null+++ b/web/app/components/tools/provider-list.tsx@@ -0,0 +1,117 @@+'use client'+import { useEffect, useMemo, useState } from 'react'+import cn from 'classnames'+import { useTranslation } from 'react-i18next'+import type { Collection } from './types'+import { useTabSearchParams } from '@/hooks/use-tab-searchparams'+import TabSliderNew from '@/app/components/base/tab-slider-new'+import LabelFilter from '@/app/components/tools/labels/filter'+import SearchInput from '@/app/components/base/search-input'+import { DotsGrid, XClose } from '@/app/components/base/icons/src/vender/line/general'+import { Colors } from '@/app/components/base/icons/src/vender/line/others'+import { Route } from '@/app/components/base/icons/src/vender/line/mapsAndTravel'+import CustomCreateCard from '@/app/components/tools/provider/custom-create-card'+import ContributeCard from '@/app/components/tools/provider/contribute'+import ProviderCard from '@/app/components/tools/provider/card'+import ProviderDetail from '@/app/components/tools/provider/detail'+import Empty from '@/app/components/tools/add-tool-modal/empty'+import { fetchCollectionList } from '@/service/tools'++const ProviderList = () => {+ const { t } = useTranslation()++ const [activeTab, setActiveTab] = useTabSearchParams({+ defaultTab: 'builtin',+ })+ const options = [+ { value: 'builtin', text: t('tools.type.builtIn'), icon: <DotsGrid className='w-[14px] h-[14px] mr-1'/> },+ { value: 'api', text: t('tools.type.custom'), icon: <Colors className='w-[14px] h-[14px] mr-1'/> },+ { value: 'workflow', text: t('tools.type.workflow'), icon: <Route className='w-[14px] h-[14px] mr-1'/> },+ ]+ const [tagFilterValue, setTagFilterValue] = useState<string[]>([])+ const handleTagsChange = (value: string[]) => {+ setTagFilterValue(value)+ }+ const [keywords, setKeywords] = useState<string>('')+ const handleKeywordsChange = (value: string) => {+ setKeywords(value)+ }++ const [collectionList, setCollectionList] = useState<Collection[]>([])+ const filteredCollectionList = useMemo(() => {+ return collectionList.filter((collection) => {+ if (collection.type !== activeTab)+ return false+ if (tagFilterValue.length > 0 && (!collection.labels || collection.labels.every(label => !tagFilterValue.includes(label))))+ return false+ if (keywords)+ return collection.name.toLowerCase().includes(keywords.toLowerCase())+ return true+ })+ }, [activeTab, tagFilterValue, keywords, collectionList])+ const getProviderList = async () => {+ const list = await fetchCollectionList()+ setCollectionList([...list])+ }+ useEffect(() => {+ getProviderList()+ }, [])++ const [currentProvider, setCurrentProvider] = useState<Collection | undefined>()+ useEffect(() => {+ if (currentProvider && collectionList.length > 0) {+ const newCurrentProvider = collectionList.find(collection => collection.id === currentProvider.id)+ setCurrentProvider(newCurrentProvider)+ }+ }, [collectionList, currentProvider])++ return (+ <div className='relative flex overflow-hidden bg-gray-100 shrink-0 h-0 grow'>+ <div className='relative flex flex-col overflow-y-auto bg-gray-100 grow'>+ <div className={cn(+ 'z-20 sticky top-0 flex justify-between items-center pt-4 px-12 pb-2 leading-[56px] bg-gray-100 flex-wrap gap-y-2',+ currentProvider && 'pr-6',+ )}>+ <TabSliderNew+ value={activeTab}+ onChange={(state) => {+ setActiveTab(state)+ if (state !== activeTab)+ setCurrentProvider(undefined)+ }}+ options={options}+ />+ <div className='flex items-center gap-2'>+ <LabelFilter value={tagFilterValue} onChange={handleTagsChange} />+ <SearchInput className='w-[200px]' value={keywords} onChange={handleKeywordsChange} />+ </div>+ </div>+ <div className={cn(+ 'relative grid content-start grid-cols-1 gap-4 px-12 pt-2 pb-4 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 grow shrink-0',+ currentProvider && 'pr-6 sm:grid-cols-1 md:grid-cols-2 lg:grid-cols-3',+ )}>+ {activeTab === 'builtin' && <ContributeCard />}+ {activeTab === 'api' && <CustomCreateCard onRefreshData={getProviderList}/>}+ {filteredCollectionList.map(collection => (+ <ProviderCard+ active={currentProvider?.id === collection.id}+ onSelect={() => setCurrentProvider(collection)}+ key={collection.id}+ collection={collection}+ />+ ))}+ {!filteredCollectionList.length && <div className='absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2'><Empty/></div>}+ </div>+ </div>+ <div className={cn(+ 'shrink-0 w-0 border-l-[0.5px] border-black/8 overflow-y-auto transition-all duration-200 ease-in-out',+ currentProvider && 'w-[420px]',+ )}>+ {currentProvider && <ProviderDetail collection={currentProvider} onRefreshData={getProviderList} />}+ </div>+ <div className='absolute top-5 right-5 p-1 cursor-pointer' onClick={() => setCurrentProvider(undefined)}><XClose className='w-4 h-4'/></div>+ </div>+ )+}+ProviderList.displayName = 'ToolProviderList'+export default ProviderListdiff --git a/web/app/components/tools/provider/card.tsx b/web/app/components/tools/provider/card.tsxnew file mode 100644index 00000000000..13009cf6548--- /dev/null+++ b/web/app/components/tools/provider/card.tsx@@ -0,0 +1,83 @@+'use client'+import { useMemo } from 'react'+import cn from 'classnames'+import { useContext } from 'use-context-selector'+import { useTranslation } from 'react-i18next'+import type { Collection } from '../types'+import AppIcon from '@/app/components/base/app-icon'+import { Tag01 } from '@/app/components/base/icons/src/vender/line/financeAndECommerce'+import I18n from '@/context/i18n'+import { getLanguage } from '@/i18n/language'+import { useStore as useLabelStore } from '@/app/components/tools/labels/store'++type Props = {+ active: boolean+ collection: Collection+ onSelect: () => void+}++const ProviderCard = ({+ active,+ collection,+ onSelect,+}: Props) => {+ const { t } = useTranslation()+ const { locale } = useContext(I18n)+ const language = getLanguage(locale)+ const labelList = useLabelStore(s => s.labelList)++ const labelContent = useMemo(() => {+ if (!collection.labels)+ return ''+ return collection.labels.map((name) => {+ const label = labelList.find(item => item.name === name)+ return label?.label[language]+ }).filter(Boolean).join(', ')+ }, [collection.labels, labelList, language])++ return (+ <div className={cn('group flex col-span-1 bg-white border-2 border-solid border-transparent rounded-xl shadow-sm min-h-[160px] flex flex-col transition-all duration-200 ease-in-out cursor-pointer hover:shadow-lg', active && '!border-primary-400')} onClick={onSelect}>+ <div className='flex pt-[14px] px-[14px] pb-3 h-[66px] items-center gap-3 grow-0 shrink-0'>+ <div className='relative shrink-0'>+ {typeof collection.icon === 'string' && (+ <div className='w-10 h-10 bg-center bg-cover bg-no-repeat rounded-md' style={{ backgroundImage: `url(${collection.icon})` }}/>+ )}+ {typeof collection.icon !== 'string' && (+ <AppIcon+ size='large'+ icon={collection.icon.content}+ background={collection.icon.background}+ />+ )}+ </div>+ <div className='grow w-0 py-[1px]'>+ <div className='flex items-center text-sm leading-5 font-semibold text-gray-800'>+ <div className='truncate' title={collection.label[language]}>{collection.label[language]}</div>+ </div>+ <div className='flex items-center text-[10px] leading-[18px] text-gray-500 font-medium'>+ <div className='truncate'>{t('tools.author')} {collection.author}</div>+ </div>+ </div>+ </div>+ <div+ className={cn(+ 'grow mb-2 px-[14px] max-h-[72px] text-xs leading-normal text-gray-500',+ collection.labels?.length ? 'line-clamp-2' : 'line-clamp-4',+ collection.labels?.length > 0 && 'group-hover:line-clamp-2 group-hover:max-h-[36px]',+ )}+ title={collection.description[language]}+ >+ {collection.description[language]}+ </div>+ {collection.labels?.length > 0 && (+ <div className='flex items-center shrink-0 mt-1 pt-1 pl-[14px] pr-[6px] pb-[6px] h-[42px]'>+ <div className='relative w-full flex items-center gap-1 py-[7px] rounded-md text-gray-500' title={labelContent}>+ <Tag01 className='shrink-0 w-3 h-3' />+ <div className='grow text-xs text-start leading-[18px] font-normal truncate'>{labelContent}</div>+ </div>+ </div>+ )}+ </div>+ )+}+export default ProviderCarddiff --git a/web/app/components/tools/provider/contribute.tsx b/web/app/components/tools/provider/contribute.tsxnew file mode 100644index 00000000000..9c3c2559b0e--- /dev/null+++ b/web/app/components/tools/provider/contribute.tsx@@ -0,0 +1,38 @@+'use client'+import type { FC } from 'react'+import React from 'react'+import { useTranslation } from 'react-i18next'+import { ToolsActive } from '@/app/components/base/icons/src/public/header-nav/tools'+import { Heart02 } from '@/app/components/base/icons/src/vender/solid/education'+import { BookOpen01 } from '@/app/components/base/icons/src/vender/line/education'+import { ArrowUpRight } from '@/app/components/base/icons/src/vender/line/arrows'++const Contribute: FC = () => {+ const { t } = useTranslation()++ return (+ <a+ href='https://github.com/langgenius/dify/blob/main/api/core/tools/README.md'+ target='_blank'+ rel='noopener noreferrer'+ className="group flex col-span-1 bg-white bg-cover bg-no-repeat bg-[url('~@/app/components/tools/provider/grid_bg.svg')] border-2 border-solid border-transparent rounded-xl shadow-sm min-h-[160px] flex-col transition-all duration-200 ease-in-out cursor-pointer hover:shadow-lg"+ >+ <div className='flex pt-[14px] px-[14px] pb-3 h-[66px] items-center gap-3 grow-0 shrink-0'>+ <div className='relative shrink-0 flex items-center'>+ <div className='z-10 flex p-3 rounded-[10px] bg-white border-[0.5px] border-primary-100 shadow-md'><ToolsActive className='w-4 h-4 text-primary-600'/></div>+ <div className='-translate-x-2 flex p-3 rounded-[10px] bg-[#FEF6FB] border-[0.5px] border-[#FCE7F6] shadow-md'><Heart02 className='w-4 h-4 text-[#EE46BC]'/></div>+ </div>+ </div>+ <div className='mb-3 px-[14px] text-[15px] leading-5 font-semibold'>+ <div className='text-gradient'>{t('tools.contribute.line1')}</div>+ <div className='text-gradient'>{t('tools.contribute.line2')}</div>+ </div>+ <div className='px-4 py-3 border-t-[0.5px] border-black/5 flex items-center space-x-1 text-[#155EEF]'>+ <BookOpen01 className='w-3 h-3' />+ <div className='grow leading-[18px] text-xs font-normal'>{t('tools.contribute.viewGuide')}</div>+ <ArrowUpRight className='w-3 h-3' />+ </div>+ </a>+ )+}+export default React.memo(Contribute)diff --git a/web/app/components/tools/provider/custom-create-card.tsx b/web/app/components/tools/provider/custom-create-card.tsxnew file mode 100644index 00000000000..f85cd21b1d2--- /dev/null+++ b/web/app/components/tools/provider/custom-create-card.tsx@@ -0,0 +1,70 @@+'use client'+import { useMemo, useState } from 'react'+import { useTranslation } from 'react-i18next'+import { useContext } from 'use-context-selector'+import type { CustomCollectionBackend } from '../types'+import I18n from '@/context/i18n'+import { getLanguage } from '@/i18n/language'+import { Plus } from '@/app/components/base/icons/src/vender/line/general'+import { BookOpen01 } from '@/app/components/base/icons/src/vender/line/education'+import { ArrowUpRight } from '@/app/components/base/icons/src/vender/line/arrows'+import EditCustomToolModal from '@/app/components/tools/edit-custom-collection-modal'+import { createCustomCollection } from '@/service/tools'+import Toast from '@/app/components/base/toast'++type Props = {+ onRefreshData: () => void+}++const Contribute = ({ onRefreshData }: Props) => {+ const { t } = useTranslation()+ const { locale } = useContext(I18n)+ const language = getLanguage(locale)++ const linkUrl = useMemo(() => {+ if (language.startsWith('zh_'))+ return 'https://docs.dify.ai/v/zh-hans/guides/gong-ju/quick-tool-integration'+ return 'https://docs.dify.ai/tutorials/quick-tool-integration'+ }, [language])++ const [isShowEditCollectionToolModal, setIsShowEditCustomCollectionModal] = useState(false)+ const doCreateCustomToolCollection = async (data: CustomCollectionBackend) => {+ await createCustomCollection(data)+ Toast.notify({+ type: 'success',+ message: t('common.api.actionSuccess'),+ })+ setIsShowEditCustomCollectionModal(false)+ onRefreshData()+ }++ return (+ <>+ <div className='flex flex-col col-span-1 bg-gray-200 border-[0.5px] border-black/5 rounded-xl min-h-[160px] transition-all duration-200 ease-in-out cursor-pointer hover:bg-gray-50 hover:shadow-lg'>+ <div className='group grow rounded-t-xl hover:bg-white' onClick={() => setIsShowEditCustomCollectionModal(true)}>+ <div className='shrink-0 flex items-center p-4 pb-3'>+ <div className='w-10 h-10 flex items-center justify-center border border-gray-200 bg-gray-100 rounded-lg group-hover:border-primary-100 group-hover:bg-primary-50'>+ <Plus className='w-4 h-4 text-gray-500 group-hover:text-primary-600'/>+ </div>+ <div className='ml-3 text-sm font-semibold leading-5 text-gray-800 group-hover:text-primary-600'>{t('tools.createCustomTool')}</div>+ </div>+ </div>+ <div className='px-4 py-3 rounded-b-xl border-t-[0.5px] border-black/5 text-gray-500 hover:text-[#155EEF] hover:bg-white'>+ <a href={linkUrl} target='_blank' rel='noopener noreferrer' className='flex items-center space-x-1'>+ <BookOpen01 className='shrink-0 w-3 h-3' />+ <div className='grow leading-[18px] text-xs font-normal truncate' title={t('tools.customToolTip') || ''}>{t('tools.customToolTip')}</div>+ <ArrowUpRight className='shrink-0 w-3 h-3' />+ </a>+ </div>+ </div>+ {isShowEditCollectionToolModal && (+ <EditCustomToolModal+ payload={null}+ onHide={() => setIsShowEditCustomCollectionModal(false)}+ onAdd={doCreateCustomToolCollection}+ />+ )}+ </>+ )+}+export default Contributediff --git a/web/app/components/tools/provider/detail.tsx b/web/app/components/tools/provider/detail.tsxnew file mode 100644index 00000000000..7eb72d328e5--- /dev/null+++ b/web/app/components/tools/provider/detail.tsx@@ -0,0 +1,343 @@+'use client'+import React, { useCallback, useEffect, useState } from 'react'+import { useTranslation } from 'react-i18next'+import { useContext } from 'use-context-selector'+import cn from 'classnames'+import { AuthHeaderPrefix, AuthType, CollectionType } from '../types'+import type { Collection, CustomCollectionBackend, Tool, WorkflowToolProviderRequest, WorkflowToolProviderResponse } from '../types'+import ToolItem from './tool-item'+import I18n from '@/context/i18n'+import { getLanguage } from '@/i18n/language'+import AppIcon from '@/app/components/base/app-icon'+import Button from '@/app/components/base/button'+import Indicator from '@/app/components/header/indicator'+import { LinkExternal02, Settings01 } from '@/app/components/base/icons/src/vender/line/general'+import ConfigCredential from '@/app/components/tools/setting/build-in/config-credentials'+import EditCustomToolModal from '@/app/components/tools/edit-custom-collection-modal'+import WorkflowToolModal from '@/app/components/tools/workflow-tool'+import Toast from '@/app/components/base/toast'+import {+ deleteWorkflowTool,+ fetchBuiltInToolList,+ fetchCustomCollection,+ fetchCustomToolList,+ fetchModelToolList,+ fetchWorkflowToolDetail,+ removeBuiltInToolCredential,+ removeCustomCollection,+ saveWorkflowToolProvider,+ updateBuiltInToolCredential,+ updateCustomCollection,+} from '@/service/tools'+import { useModalContext } from '@/context/modal-context'+import { useProviderContext } from '@/context/provider-context'+import { ConfigurateMethodEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'+import Loading from '@/app/components/base/loading'++type Props = {+ collection: Collection+ onRefreshData: () => void+}++const ProviderDetail = ({+ collection,+ onRefreshData,+}: Props) => {+ const { t } = useTranslation()+ const { locale } = useContext(I18n)+ const language = getLanguage(locale)++ const needAuth = collection.allow_delete || collection.type === CollectionType.model+ const isAuthed = collection.is_team_authorization+ const isBuiltIn = collection.type === CollectionType.builtIn+ const isModel = collection.type === CollectionType.model++ const [isDetailLoading, setIsDetailLoading] = useState(false)++ // built in provider+ const [showSettingAuth, setShowSettingAuth] = useState(false)+ const { setShowModelModal } = useModalContext()+ const { modelProviders: providers } = useProviderContext()+ const showSettingAuthModal = () => {+ if (isModel) {+ const provider = providers.find(item => item.provider === collection?.id)+ if (provider) {+ setShowModelModal({+ payload: {+ currentProvider: provider,+ currentConfigurateMethod: ConfigurateMethodEnum.predefinedModel,+ currentCustomConfigrationModelFixedFields: undefined,+ },+ onSaveCallback: () => {+ onRefreshData()+ },+ })+ }+ }+ else {+ setShowSettingAuth(true)+ }+ }+ // custom provider+ const [customCollection, setCustomCollection] = useState<CustomCollectionBackend | WorkflowToolProviderResponse | null>(null)+ const [isShowEditCollectionToolModal, setIsShowEditCustomCollectionModal] = useState(false)+ const doUpdateCustomToolCollection = async (data: CustomCollectionBackend) => {+ await updateCustomCollection(data)+ onRefreshData()+ Toast.notify({+ type: 'success',+ message: t('common.api.actionSuccess'),+ })+ setIsShowEditCustomCollectionModal(false)+ }+ const doRemoveCustomToolCollection = async () => {+ await removeCustomCollection(collection?.name as string)+ onRefreshData()+ Toast.notify({+ type: 'success',+ message: t('common.api.actionSuccess'),+ })+ setIsShowEditCustomCollectionModal(false)+ }+ const getCustomProvider = useCallback(async () => {+ setIsDetailLoading(true)+ const res = await fetchCustomCollection(collection.name)+ if (res.credentials.auth_type === AuthType.apiKey && !res.credentials.api_key_header_prefix) {+ if (res.credentials.api_key_value)+ res.credentials.api_key_header_prefix = AuthHeaderPrefix.custom+ }+ setCustomCollection({+ ...res,+ labels: collection.labels,+ provider: collection.name,+ })+ setIsDetailLoading(false)+ }, [collection.name])+ // workflow provider+ const [isShowEditWorkflowToolModal, setIsShowEditWorkflowToolModal] = useState(false)+ const getWorkflowToolProvider = useCallback(async () => {+ setIsDetailLoading(true)+ const res = await fetchWorkflowToolDetail(collection.id)+ const payload = {+ ...res,+ parameters: res.tool?.parameters.map((item) => {+ return {+ name: item.name,+ description: item.llm_description,+ form: item.form,+ required: item.required,+ type: item.type,+ }+ }) || [],+ labels: res.tool?.labels || [],+ }+ setCustomCollection(payload)+ setIsDetailLoading(false)+ }, [collection.id])+ const removeWorkflowToolProvider = async () => {+ await deleteWorkflowTool(collection.id)+ onRefreshData()+ Toast.notify({+ type: 'success',+ message: t('common.api.actionSuccess'),+ })+ setIsShowEditWorkflowToolModal(false)+ }+ const updateWorkflowToolProvider = async (data: WorkflowToolProviderRequest & Partial<{+ workflow_app_id: string+ workflow_tool_id: string+ }>) => {+ await saveWorkflowToolProvider(data)+ onRefreshData()+ getWorkflowToolProvider()+ Toast.notify({+ type: 'success',+ message: t('common.api.actionSuccess'),+ })+ setIsShowEditWorkflowToolModal(false)+ }++ // ToolList+ const [toolList, setToolList] = useState<Tool[]>([])+ const getProviderToolList = useCallback(async () => {+ setIsDetailLoading(true)+ try {+ if (collection.type === CollectionType.builtIn) {+ const list = await fetchBuiltInToolList(collection.name)+ setToolList(list)+ }+ else if (collection.type === CollectionType.model) {+ const list = await fetchModelToolList(collection.name)+ setToolList(list)+ }+ else if (collection.type === CollectionType.workflow) {+ setToolList([])+ }+ else {+ const list = await fetchCustomToolList(collection.name)+ setToolList(list)+ }+ }+ catch (e) { }+ setIsDetailLoading(false)+ }, [collection.name, collection.type])++ useEffect(() => {+ if (collection.type === CollectionType.custom)+ getCustomProvider()+ if (collection.type === CollectionType.workflow)+ getWorkflowToolProvider()+ getProviderToolList()+ }, [collection.name, collection.type, getCustomProvider, getProviderToolList, getWorkflowToolProvider])++ return (+ <div className='px-6 py-3'>+ <div className='flex items-center py-1 gap-2'>+ <div className='relative shrink-0'>+ {typeof collection.icon === 'string' && (+ <div className='w-8 h-8 bg-center bg-cover bg-no-repeat rounded-md' style={{ backgroundImage: `url(${collection.icon})` }}/>+ )}+ {typeof collection.icon !== 'string' && (+ <AppIcon+ size='small'+ icon={collection.icon.content}+ background={collection.icon.background}+ />+ )}+ </div>+ <div className='grow w-0 py-[1px]'>+ <div className='flex items-center text-md leading-6 font-semibold text-gray-900'>+ <div className='truncate' title={collection.label[language]}>{collection.label[language]}</div>+ </div>+ </div>+ </div>+ <div className='mt-2 min-h-[36px] text-gray-500 text-sm leading-[18px]'>{collection.description[language]}</div>+ <div className='flex gap-1 border-b-[0.5px] border-black/5'>+ {(collection.type === CollectionType.builtIn) && needAuth && (+ <Button+ type={isAuthed ? 'default' : 'primary'}+ className={cn('shrink-0 my-3 w-full flex items-center', isAuthed && 'bg-white')}+ onClick={() => {+ if (collection.type === CollectionType.builtIn || collection.type === CollectionType.model)+ showSettingAuthModal()+ }}+ >+ {isAuthed && <Indicator className='mr-2' color={'green'} />}+ <div className={cn('text-white leading-[18px] text-[13px] font-medium', isAuthed && '!text-gray-700')}>+ {isAuthed ? t('tools.auth.authorized') : t('tools.auth.unauthorized')}+ </div>+ </Button>+ )}+ {collection.type === CollectionType.custom && !isDetailLoading && (+ <Button+ className={cn('shrink-0 my-3 w-full flex items-center bg-white')}+ onClick={() => setIsShowEditCustomCollectionModal(true)}+ >+ <Settings01 className='mr-1 w-4 h-4 text-gray-500' />+ <div className='leading-5 text-sm font-medium text-gray-700'>{t('tools.createTool.editAction')}</div>+ </Button>+ )}+ {collection.type === CollectionType.workflow && !isDetailLoading && customCollection && (+ <>+ <Button+ type='primary'+ className={cn('shrink-0 my-3 w-[183px] flex items-center')}+ >+ <a className='flex items-center text-white' href={`/app/${(customCollection as WorkflowToolProviderResponse).workflow_app_id}/workflow`} rel='noreferrer' target='_blank'>+ <div className='leading-5 text-sm font-medium'>{t('tools.openInStudio')}</div>+ <LinkExternal02 className='ml-1 w-4 h-4' />+ </a>+ </Button>+ <Button+ className={cn('shrink-0 my-3 w-[183px] flex items-center bg-white')}+ onClick={() => setIsShowEditWorkflowToolModal(true)}+ >+ <div className='leading-5 text-sm font-medium text-gray-700'>{t('tools.createTool.editAction')}</div>+ </Button>+ </>+ )}+ </div>+ {/* Tools */}+ <div className='pt-3'>+ {isDetailLoading && <div className='flex h-[200px]'><Loading type='app'/></div>}+ {!isDetailLoading && (+ <div className='text-xs font-medium leading-6 text-gray-500'>+ {collection.type === CollectionType.workflow && <span className=''>{t('tools.createTool.toolInput.title').toLocaleUpperCase()}</span>}+ {collection.type !== CollectionType.workflow && <span className=''>{t('tools.includeToolNum', { num: toolList.length }).toLocaleUpperCase()}</span>}+ {needAuth && (isBuiltIn || isModel) && !isAuthed && (+ <>+ <span className='px-1'>·</span>+ <span className='text-[#DC6803]'>{t('tools.auth.setup').toLocaleUpperCase()}</span>+ </>+ )}+ </div>+ )}+ {!isDetailLoading && (+ <div className='mt-1'>+ {collection.type !== CollectionType.workflow && toolList.map(tool => (+ <ToolItem+ key={tool.name}+ disabled={needAuth && (isBuiltIn || isModel) && !isAuthed}+ collection={collection}+ tool={tool}+ isBuiltIn={isBuiltIn}+ isModel={isModel}+ />+ ))}+ {collection.type === CollectionType.workflow && (customCollection as WorkflowToolProviderResponse)?.tool?.parameters.map(item => (+ <div key={item.name} className='mb-2 px-4 py-3 rounded-xl bg-gray-25 border-[0.5px] border-gray-200'>+ <div className='flex items-center gap-2'>+ <span className='font-medium text-sm text-gray-900'>{item.name}</span>+ <span className='text-xs leading-[18px] text-gray-500'>{item.type}</span>+ <span className='font-medium text-xs leading-[18px] text-[#ec4a0a]'>{item.required ? t('tools.createTool.toolInput.required') : ''}</span>+ </div>+ <div className='h-[18px] leading-[18px] text-gray-500 text-xs'>{item.llm_description}</div>+ </div>+ ))}+ </div>+ )}+ </div>+ {showSettingAuth && (+ <ConfigCredential+ collection={collection}+ onCancel={() => setShowSettingAuth(false)}+ onSaved={async (value) => {+ await updateBuiltInToolCredential(collection.name, value)+ Toast.notify({+ type: 'success',+ message: t('common.api.actionSuccess'),+ })+ await onRefreshData()+ setShowSettingAuth(false)+ }}+ onRemove={async () => {+ await removeBuiltInToolCredential(collection.name)+ Toast.notify({+ type: 'success',+ message: t('common.api.actionSuccess'),+ })+ await onRefreshData()+ setShowSettingAuth(false)+ }}+ />+ )}+ {isShowEditCollectionToolModal && (+ <EditCustomToolModal+ payload={customCollection}+ onHide={() => setIsShowEditCustomCollectionModal(false)}+ onEdit={doUpdateCustomToolCollection}+ onRemove={doRemoveCustomToolCollection}+ />+ )}+ {isShowEditWorkflowToolModal && (+ <WorkflowToolModal+ payload={customCollection}+ onHide={() => setIsShowEditWorkflowToolModal(false)}+ onRemove={removeWorkflowToolProvider}+ onSave={updateWorkflowToolProvider}+ />+ )}+ </div>+ )+}+export default ProviderDetaildiff --git a/web/app/components/tools/provider/grid_bg.svg b/web/app/components/tools/provider/grid_bg.svgnew file mode 100644index 00000000000..8b0f5319595--- /dev/null+++ b/web/app/components/tools/provider/grid_bg.svg@@ -0,0 +1,14 @@+<svg width="345" height="118" viewBox="0 0 345 118" fill="none" xmlns="http://www.w3.org/2000/svg">+<mask id="mask0_17759_72539" style="mask-type:alpha" maskUnits="userSpaceOnUse" x="0" y="0" width="345" height="118">+<rect width="345" height="118" fill="url(#paint0_linear_17759_72539)"/>+</mask>+<g mask="url(#mask0_17759_72539)">+<path d="M8 0H0V8M8 0V8M8 0H16M8 8H0M8 8H16M8 8V16M0 8V16M16 0V8M16 0H24M16 8H24M16 8V16M24 0V8M24 0H32M24 8H32M24 8V16M32 0V8M32 0H40M32 8H40M32 8V16M40 0V8M40 0H48M40 8H48M40 8V16M48 0V8M48 0H56M48 8H56M48 8V16M56 0V8M56 0H64M56 8H64M56 8V16M64 0V8M64 0H72M64 8H72M64 8V16M72 0V8M72 0H80M72 8H80M72 8V16M80 0V8M80 0H88M80 8H88M80 8V16M88 0V8M88 0H96M88 8H96M88 8V16M96 0V8M96 0H104M96 8H104M96 8V16M104 0V8M104 0H112M104 8H112M104 8V16M112 0V8M112 0H120M112 8H120M112 8V16M120 0V8M120 0H128M120 8H128M120 8V16M128 0V8M128 0H136M128 8H136M128 8V16M136 0V8M136 0H144M136 8H144M136 8V16M144 0V8M144 0H152M144 8H152M144 8V16M152 0V8M152 0H160M152 8H160M152 8V16M160 0V8M160 0H168M160 8H168M160 8V16M168 0V8M168 0H176M168 8H176M168 8V16M176 0V8M176 0H184M176 8H184M176 8V16M184 0V8M184 0H192M184 8H192M184 8V16M192 0V8M192 0H200M192 8H200M192 8V16M200 0V8M200 0H208M200 8H208M200 8V16M208 0V8M208 0H216M208 8H216M208 8V16M216 0V8M216 0H224M216 8H224M216 8V16M224 0V8M224 0H232M224 8H232M224 8V16M232 0V8M232 0H240M232 8H240M232 8V16M240 0V8M240 0H248M240 8H248M240 8V16M248 0V8M248 0H256M248 8H256M248 8V16M256 0V8M256 0H264M256 8H264M256 8V16M264 0V8M264 0H272M264 8H272M264 8V16M272 0V8M272 0H280M272 8H280M272 8V16M280 0V8M280 0H288M280 8V16M280 8H288M8 16H0M8 16H16M8 16V24M0 16V24M16 16H24M16 16V24M24 16H32M24 16V24M32 16H40M32 16V24M40 16H48M40 16V24M48 16H56M48 16V24M56 16H64M56 16V24M64 16H72M64 16V24M72 16H80M72 16V24M80 16H88M80 16V24M88 16H96M88 16V24M96 16H104M96 16V24M104 16H112M104 16V24M112 16H120M112 16V24M120 16H128M120 16V24M128 16H136M128 16V24M136 16H144M136 16V24M144 16H152M144 16V24M152 16H160M152 16V24M160 16H168M160 16V24M168 16H176M168 16V24M176 16H184M176 16V24M184 16H192M184 16V24M192 16H200M192 16V24M200 16H208M200 16V24M208 16H216M208 16V24M216 16H224M216 16V24M224 16H232M224 16V24M232 16H240M232 16V24M240 16H248M240 16V24M248 16H256M248 16V24M256 16H264M256 16V24M264 16H272M264 16V24M272 16H280M272 16V24M280 16V24M280 16H288M8 24H0M8 24H16M8 24V32M0 24V32M16 24H24M16 24V32M24 24H32M24 24V32M32 24H40M32 24V32M40 24H48M40 24V32M48 24H56M48 24V32M56 24H64M56 24V32M64 24H72M64 24V32M72 24H80M72 24V32M80 24H88M80 24V32M88 24H96M88 24V32M96 24H104M96 24V32M104 24H112M104 24V32M112 24H120M112 24V32M120 24H128M120 24V32M128 24H136M128 24V32M136 24H144M136 24V32M144 24H152M144 24V32M152 24H160M152 24V32M160 24H168M160 24V32M168 24H176M168 24V32M176 24H184M176 24V32M184 24H192M184 24V32M192 24H200M192 24V32M200 24H208M200 24V32M208 24H216M208 24V32M216 24H224M216 24V32M224 24H232M224 24V32M232 24H240M232 24V32M240 24H248M240 24V32M248 24H256M248 24V32M256 24H264M256 24V32M264 24H272M264 24V32M272 24H280M272 24V32M280 24V32M280 24H288M8 32H0M8 32H16M8 32V40M0 32V40M16 32H24M16 32V40M24 32H32M24 32V40M32 32H40M32 32V40M40 32H48M40 32V40M48 32H56M48 32V40M56 32H64M56 32V40M64 32H72M64 32V40M72 32H80M72 32V40M80 32H88M80 32V40M88 32H96M88 32V40M96 32H104M96 32V40M104 32H112M104 32V40M112 32H120M112 32V40M120 32H128M120 32V40M128 32H136M128 32V40M136 32H144M136 32V40M144 32H152M144 32V40M152 32H160M152 32V40M160 32H168M160 32V40M168 32H176M168 32V40M176 32H184M176 32V40M184 32H192M184 32V40M192 32H200M192 32V40M200 32H208M200 32V40M208 32H216M208 32V40M216 32H224M216 32V40M224 32H232M224 32V40M232 32H240M232 32V40M240 32H248M240 32V40M248 32H256M248 32V40M256 32H264M256 32V40M264 32H272M264 32V40M272 32H280M272 32V40M280 32V40M280 32H288M8 40H0M8 40H16M8 40V48M0 40V48M16 40H24M16 40V48M24 40H32M24 40V48M32 40H40M32 40V48M40 40H48M40 40V48M48 40H56M48 40V48M56 40H64M56 40V48M64 40H72M64 40V48M72 40H80M72 40V48M80 40H88M80 40V48M88 40H96M88 40V48M96 40H104M96 40V48M104 40H112M104 40V48M112 40H120M112 40V48M120 40H128M120 40V48M128 40H136M128 40V48M136 40H144M136 40V48M144 40H152M144 40V48M152 40H160M152 40V48M160 40H168M160 40V48M168 40H176M168 40V48M176 40H184M176 40V48M184 40H192M184 40V48M192 40H200M192 40V48M200 40H208M200 40V48M208 40H216M208 40V48M216 40H224M216 40V48M224 40H232M224 40V48M232 40H240M232 40V48M240 40H248M240 40V48M248 40H256M248 40V48M256 40H264M256 40V48M264 40H272M264 40V48M272 40H280M272 40V48M280 40V48M280 40H288M8 48H0M8 48H16M8 48V56M0 48V56M16 48H24M16 48V56M24 48H32M24 48V56M32 48H40M32 48V56M40 48H48M40 48V56M48 48H56M48 48V56M56 48H64M56 48V56M64 48H72M64 48V56M72 48H80M72 48V56M80 48H88M80 48V56M88 48H96M88 48V56M96 48H104M96 48V56M104 48H112M104 48V56M112 48H120M112 48V56M120 48H128M120 48V56M128 48H136M128 48V56M136 48H144M136 48V56M144 48H152M144 48V56M152 48H160M152 48V56M160 48H168M160 48V56M168 48H176M168 48V56M176 48H184M176 48V56M184 48H192M184 48V56M192 48H200M192 48V56M200 48H208M200 48V56M208 48H216M208 48V56M216 48H224M216 48V56M224 48H232M224 48V56M232 48H240M232 48V56M240 48H248M240 48V56M248 48H256M248 48V56M256 48H264M256 48V56M264 48H272M264 48V56M272 48H280M272 48V56M280 48V56M280 48H288M8 56H0M8 56H16M8 56V64M0 56V64M16 56H24M16 56V64M24 56H32M24 56V64M32 56H40M32 56V64M40 56H48M40 56V64M48 56H56M48 56V64M56 56H64M56 56V64M64 56H72M64 56V64M72 56H80M72 56V64M80 56H88M80 56V64M88 56H96M88 56V64M96 56H104M96 56V64M104 56H112M104 56V64M112 56H120M112 56V64M120 56H128M120 56V64M128 56H136M128 56V64M136 56H144M136 56V64M144 56H152M144 56V64M152 56H160M152 56V64M160 56H168M160 56V64M168 56H176M168 56V64M176 56H184M176 56V64M184 56H192M184 56V64M192 56H200M192 56V64M200 56H208M200 56V64M208 56H216M208 56V64M216 56H224M216 56V64M224 56H232M224 56V64M232 56H240M232 56V64M240 56H248M240 56V64M248 56H256M248 56V64M256 56H264M256 56V64M264 56H272M264 56V64M272 56H280M272 56V64M280 56V64M280 56H288M8 64H0M8 64H16M8 64V72M0 64V72M16 64H24M16 64V72M24 64H32M24 64V72M32 64H40M32 64V72M40 64H48M40 64V72M48 64H56M48 64V72M56 64H64M56 64V72M64 64H72M64 64V72M72 64H80M72 64V72M80 64H88M80 64V72M88 64H96M88 64V72M96 64H104M96 64V72M104 64H112M104 64V72M112 64H120M112 64V72M120 64H128M120 64V72M128 64H136M128 64V72M136 64H144M136 64V72M144 64H152M144 64V72M152 64H160M152 64V72M160 64H168M160 64V72M168 64H176M168 64V72M176 64H184M176 64V72M184 64H192M184 64V72M192 64H200M192 64V72M200 64H208M200 64V72M208 64H216M208 64V72M216 64H224M216 64V72M224 64H232M224 64V72M232 64H240M232 64V72M240 64H248M240 64V72M248 64H256M248 64V72M256 64H264M256 64V72M264 64H272M264 64V72M272 64H280M272 64V72M280 64V72M280 64H288M8 72H0M8 72H16M8 72V80M0 72V80M16 72H24M16 72V80M24 72H32M24 72V80M32 72H40M32 72V80M40 72H48M40 72V80M48 72H56M48 72V80M56 72H64M56 72V80M64 72H72M64 72V80M72 72H80M72 72V80M80 72H88M80 72V80M88 72H96M88 72V80M96 72H104M96 72V80M104 72H112M104 72V80M112 72H120M112 72V80M120 72H128M120 72V80M128 72H136M128 72V80M136 72H144M136 72V80M144 72H152M144 72V80M152 72H160M152 72V80M160 72H168M160 72V80M168 72H176M168 72V80M176 72H184M176 72V80M184 72H192M184 72V80M192 72H200M192 72V80M200 72H208M200 72V80M208 72H216M208 72V80M216 72H224M216 72V80M224 72H232M224 72V80M232 72H240M232 72V80M240 72H248M240 72V80M248 72H256M248 72V80M256 72H264M256 72V80M264 72H272M264 72V80M272 72H280M272 72V80M280 72V80M280 72H288M8 80H0M8 80H16M8 80V88M0 80L0 88M16 80H24M16 80V88M24 80H32M24 80V88M32 80H40M32 80V88M40 80H48M40 80V88M48 80H56M48 80V88M56 80H64M56 80V88M64 80H72M64 80V88M72 80H80M72 80V88M80 80H88M80 80V88M88 80H96M88 80V88M96 80H104M96 80V88M104 80H112M104 80V88M112 80H120M112 80V88M120 80H128M120 80V88M128 80H136M128 80V88M136 80H144M136 80V88M144 80H152M144 80V88M152 80H160M152 80V88M160 80H168M160 80V88M168 80H176M168 80V88M176 80H184M176 80V88M184 80H192M184 80V88M192 80H200M192 80V88M200 80H208M200 80V88M208 80H216M208 80V88M216 80H224M216 80V88M224 80H232M224 80V88M232 80H240M232 80V88M240 80H248M240 80V88M248 80H256M248 80V88M256 80H264M256 80V88M264 80H272M264 80V88M272 80H280M272 80V88M280 80H288M280 80V88M288 0V8M288 0H296M288 8H296M288 8V16M296 0V8M296 0H304M296 8H304M296 8V16M304 0V8M304 0H312M304 8H312M304 8V16M312 0V8M312 0H320M312 8H320M312 8V16M320 0V8M320 0H328M320 8H328M320 8V16M328 0V8M328 0H336M328 8H336M328 8V16M336 0V8M336 0H344V8M336 8H344M336 8V16M344 8V16M288 16H296M288 16V24M296 16H304M296 16V24M304 16H312M304 16V24M312 16H320M312 16V24M320 16H328M320 16V24M328 16H336M328 16V24M336 16H344M336 16V24M344 16V24M288 24H296M288 24V32M296 24H304M296 24V32M304 24H312M304 24V32M312 24H320M312 24V32M320 24H328M320 24V32M328 24H336M328 24V32M336 24H344M336 24V32M344 24V32M288 32H296M288 32V40M296 32H304M296 32V40M304 32H312M304 32V40M312 32H320M312 32V40M320 32H328M320 32V40M328 32H336M328 32V40M336 32H344M336 32V40M344 32V40M288 40H296M288 40V48M296 40H304M296 40V48M304 40H312M304 40V48M312 40H320M312 40V48M320 40H328M320 40V48M328 40H336M328 40V48M336 40H344M336 40V48M344 40V48M288 48H296M288 48V56M296 48H304M296 48V56M304 48H312M304 48V56M312 48H320M312 48V56M320 48H328M320 48V56M328 48H336M328 48V56M336 48H344M336 48V56M344 48V56M288 56H296M288 56V64M296 56H304M296 56V64M304 56H312M304 56V64M312 56H320M312 56V64M320 56H328M320 56V64M328 56H336M328 56V64M336 56H344M336 56V64M344 56V64M288 64H296M288 64V72M296 64H304M296 64V72M304 64H312M304 64V72M312 64H320M312 64V72M320 64H328M320 64V72M328 64H336M328 64V72M336 64H344M336 64V72M344 64V72M288 72H296M288 72V80M296 72H304M296 72V80M304 72H312M304 72V80M312 72H320M312 72V80M320 72H328M320 72V80M328 72H336M328 72V80M336 72H344M336 72V80M344 72V80M288 80H296M288 80V88M296 80H304M296 80V88M304 80H312M304 80V88M312 80H320M312 80V88M320 80H328M320 80V88M328 80H336M328 80V88M336 80H344M336 80V88M344 80V88M8 88H0M8 88H16M8 88V96M0 88V96M16 88H24M16 88V96M24 88H32M24 88V96M32 88H40M32 88V96M40 88H48M40 88V96M48 88H56M48 88V96M56 88H64M56 88V96M64 88H72M64 88V96M72 88H80M72 88V96M80 88H88M80 88V96M88 88H96M88 88V96M96 88H104M96 88V96M104 88H112M104 88V96M112 88H120M112 88V96M120 88H128M120 88V96M128 88H136M128 88V96M136 88H144M136 88V96M144 88H152M144 88V96M152 88H160M152 88V96M160 88H168M160 88V96M168 88H176M168 88V96M176 88H184M176 88V96M184 88H192M184 88V96M192 88H200M192 88V96M200 88H208M200 88V96M208 88H216M208 88V96M216 88H224M216 88V96M224 88H232M224 88V96M232 88H240M232 88V96M240 88H248M240 88V96M248 88H256M248 88V96M256 88H264M256 88V96M264 88H272M264 88V96M272 88H280M272 88V96M280 88V96M280 88H288M8 96H0M8 96H16M8 96V104M0 96V104M16 96H24M16 96V104M24 96H32M24 96V104M32 96H40M32 96V104M40 96H48M40 96V104M48 96H56M48 96V104M56 96H64M56 96V104M64 96H72M64 96V104M72 96H80M72 96V104M80 96H88M80 96V104M88 96H96M88 96V104M96 96H104M96 96V104M104 96H112M104 96V104M112 96H120M112 96V104M120 96H128M120 96V104M128 96H136M128 96V104M136 96H144M136 96V104M144 96H152M144 96V104M152 96H160M152 96V104M160 96H168M160 96V104M168 96H176M168 96V104M176 96H184M176 96V104M184 96H192M184 96V104M192 96H200M192 96V104M200 96H208M200 96V104M208 96H216M208 96V104M216 96H224M216 96V104M224 96H232M224 96V104M232 96H240M232 96V104M240 96H248M240 96V104M248 96H256M248 96V104M256 96H264M256 96V104M264 96H272M264 96V104M272 96H280M272 96V104M280 96V104M280 96H288M8 104H0M8 104H16M8 104V112M0 104V112H8M16 104H24M16 104V112M24 104H32M24 104V112M32 104H40M32 104V112M40 104H48M40 104V112M48 104H56M48 104V112M56 104H64M56 104V112M64 104H72M64 104V112M72 104H80M72 104V112M80 104H88M80 104V112M88 104H96M88 104V112M96 104H104M96 104V112M104 104H112M104 104V112M112 104H120M112 104V112M120 104H128M120 104V112M128 104H136M128 104V112M136 104H144M136 104V112M144 104H152M144 104V112M152 104H160M152 104V112M160 104H168M160 104V112M168 104H176M168 104V112M176 104H184M176 104V112M184 104H192M184 104V112M192 104H200M192 104V112M200 104H208M200 104V112M208 104H216M208 104V112M216 104H224M216 104V112M224 104H232M224 104V112M232 104H240M232 104V112M240 104H248M240 104V112M248 104H256M248 104V112M256 104H264M256 104V112M264 104H272M264 104V112M272 104H280M272 104V112M280 104V112M280 104H288M8 112H16M16 112H24M24 112H32M32 112H40M40 112H48M48 112H56M56 112H64M64 112H72M72 112H80M80 112H88M88 112H96M96 112H104M104 112H112M112 112H120M120 112H128M128 112H136M136 112H144M144 112H152M152 112H160M160 112H168M168 112H176M176 112H184M184 112H192M192 112H200M200 112H208M208 112H216M216 112H224M224 112H232M232 112H240M240 112H248M248 112H256M256 112H264M264 112H272M272 112H280M280 112H288M288 88H296M288 88V96M296 88H304M296 88V96M304 88H312M304 88V96M312 88H320M312 88V96M320 88H328M320 88V96M328 88H336M328 88V96M336 88H344M336 88V96M344 88V96M288 96H296M288 96V104M296 96H304M296 96V104M304 96H312M304 96V104M312 96H320M312 96V104M320 96H328M320 96V104M328 96H336M328 96V104M336 96H344M336 96V104M344 96V104M288 104H296M288 104V112M296 104H304M296 104V112M304 104H312M304 104V112M312 104H320M312 104V112M320 104H328M320 104V112M328 104H336M328 104V112M336 104H344M336 104V112M344 104V112H336M288 112H296M296 112H304M304 112H312M312 112H320M320 112H328M328 112H336" stroke="#1570EF" stroke-width="0.5"/>+</g>+<defs>+<linearGradient id="paint0_linear_17759_72539" x1="172.5" y1="0" x2="172.5" y2="118" gradientUnits="userSpaceOnUse">+<stop stop-color="#D9D9D9" stop-opacity="0.08"/>+<stop offset="1" stop-color="#737373" stop-opacity="0"/>+</linearGradient>+</defs>+</svg>diff --git a/web/app/components/tools/provider/tool-item.tsx b/web/app/components/tools/provider/tool-item.tsxnew file mode 100644index 00000000000..f373186a0aa--- /dev/null+++ b/web/app/components/tools/provider/tool-item.tsx@@ -0,0 +1,53 @@+'use client'+import React, { useState } from 'react'+import cn from 'classnames'+import { useContext } from 'use-context-selector'+import type { Collection, Tool } from '../types'+import I18n from '@/context/i18n'+import { getLanguage } from '@/i18n/language'+import SettingBuiltInTool from '@/app/components/app/configuration/config/agent/agent-tools/setting-built-in-tool'++type Props = {+ disabled?: boolean+ collection: Collection+ tool: Tool+ isBuiltIn: boolean+ isModel: boolean+}++const ToolItem = ({+ disabled,+ collection,+ tool,+ isBuiltIn,+ isModel,+}: Props) => {+ const { locale } = useContext(I18n)+ const language = getLanguage(locale)+ const [showDetail, setShowDetail] = useState(false)++ return (+ <>+ <div+ className={cn('mb-2 px-4 py-3 rounded-xl bg-gray-25 border-[0.5px] border-gary-200 shadow-xs cursor-pointer', disabled && 'opacity-50 !cursor-not-allowed')}+ onClick={() => !disabled && setShowDetail(true)}+ >+ <div className='text-gray-800 font-semibold text-sm leading-5'>{tool.label[language]}</div>+ <div className='mt-0.5 text-xs leading-[18px] text-gray-500 line-clamp-2' title={tool.description[language]}>{tool.description[language]}</div>+ </div>+ {showDetail && (+ <SettingBuiltInTool+ collection={collection}+ toolName={tool.name}+ readonly+ onHide={() => {+ setShowDetail(false)+ }}+ isBuiltIn={isBuiltIn}+ isModel={isModel}+ />+ )}+ </>+ )+}+export default ToolItemdiff --git a/web/app/components/tools/search.tsx b/web/app/components/tools/search.tsxdeleted file mode 100644index 344d84069e5..00000000000--- a/web/app/components/tools/search.tsx+++ /dev/null@@ -1,41 +0,0 @@-'use client'-import type { FC } from 'react'-import React from 'react'-import cn from 'classnames'-import {- MagnifyingGlassIcon,-} from '@heroicons/react/24/solid'-import { useTranslation } from 'react-i18next'--type Props = {- className?: string- value: string- onChange: (v: string) => void-}--const Search: FC<Props> = ({- className,- value,- onChange,-}) => {- const { t } = useTranslation()-- return (- <div className={cn(className, 'flex relative')}>- <div className="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3">- <MagnifyingGlassIcon className="h-5 w-5 text-gray-400" aria-hidden="true" />- </div>- <input- type="text"- name="query"- className="block w-0 grow bg-gray-200 shadow-sm rounded-md border-0 pl-10 text-gray-900 placeholder:text-gray-400 focus:ring-1 focus:ring-inset focus:ring-gray-200 focus-visible:outline-none sm:text-sm sm:leading-8"- placeholder={t('common.operation.search')!}- value={value}- onChange={(e) => {- onChange(e.target.value)- }}- />- </div>- )-}-export default React.memo(Search)diff --git a/web/app/components/tools/setting/build-in/config-credentials.tsx b/web/app/components/tools/setting/build-in/config-credentials.tsxindex b663f96afef..fcfca8f2398 100644--- a/web/app/components/tools/setting/build-in/config-credentials.tsx+++ b/web/app/components/tools/setting/build-in/config-credentials.tsx@@ -48,8 +48,8 @@ const ConfigCredential: FC<Props> = ({onHide={onCancel}title={t('tools.auth.setupModalTitle') as string}titleDescription={t('tools.auth.setupModalTitleDescription') as string}- panelClassName='mt-2 !w-[480px]'- maxWidthClassName='!max-w-[480px]'+ panelClassName='mt-2 !w-[405px]'+ maxWidthClassName='!max-w-[405px]'height='calc(100vh - 16px)'contentClassName='!bg-gray-100'headerClassName='!border-b-black/5'@@ -88,7 +88,7 @@ const ConfigCredential: FC<Props> = ({)}< div className='flex space-x-2'>- <Button className='flex items-center h-8 !px-3 !text-[13px] font-medium !text-gray-700' onClick={onCancel}>{t('common.operation.cancel')}</Button>+ <Button className='flex items-center h-8 !px-3 !text-[13px] font-medium !text-gray-700 bg-white' onClick={onCancel}>{t('common.operation.cancel')}</Button><Button className='flex items-center h-8 !px-3 !text-[13px] font-medium' type='primary' onClick={() => onSaved(tempCredential)}>{t('common.operation.save')}</Button></div></div>diff --git a/web/app/components/tools/tool-list/header.tsx b/web/app/components/tools/tool-list/header.tsxdeleted file mode 100644index bf564f320f7..00000000000--- a/web/app/components/tools/tool-list/header.tsx+++ /dev/null@@ -1,77 +0,0 @@-'use client'-import type { FC } from 'react'-import React from 'react'-import { useContext } from 'use-context-selector'-import cn from 'classnames'-import { useTranslation } from 'react-i18next'-import type { Collection } from '../types'-import { CollectionType, LOC } from '../types'-import { Settings01 } from '../../base/icons/src/vender/line/general'-import I18n from '@/context/i18n'-import { getLanguage } from '@/i18n/language'-type Props = {- icon: JSX.Element- collection: Collection- loc: LOC- onShowAuth: () => void- onShowEditCustomCollection: () => void-}--const Header: FC<Props> = ({- icon,- collection,- loc,- onShowAuth,- onShowEditCustomCollection,-}) => {- const { locale } = useContext(I18n)- const language = getLanguage(locale)- const { t } = useTranslation()- const isInToolsPage = loc === LOC.tools- const isInDebugPage = !isInToolsPage-- const needAuth = collection?.allow_delete || collection?.type === CollectionType.model- const isAuthed = collection.is_team_authorization- return (- <div className={cn(isInToolsPage ? 'py-4 px-6' : 'py-[11px] pl-4 pr-3', 'flex justify-between items-start border-b border-gray-200')}>- <div className='flex items-start w-full'>- {icon}- <div className='ml-3 grow w-0'>- <div className='flex items-center h-6 space-x-1'>- <div className={cn(isInDebugPage && 'truncate', 'text-base font-semibold text-gray-900')}>{collection.label[language]}</div>- <div className='text-xs font-normal text-gray-500'>·</div>- <div className='text-xs font-normal text-gray-500'>{t('tools.author')} {collection.author}</div>- </div>- {collection.description && (- <div className={cn('leading-[18px] text-[13px] font-normal text-gray-500')}>- {collection.description[language]}- </div>- )}- </div>- </div>- {(collection.type === CollectionType.builtIn || collection.type === CollectionType.model) && needAuth && (- <div- className={cn('cursor-pointer', 'ml-1 shrink-0 flex items-center h-8 border border-gray-200 rounded-lg px-3 space-x-2 shadow-xs')}- onClick={() => {- if (collection.type === CollectionType.builtIn || collection.type === CollectionType.model)- onShowAuth()- }}- >- <div className={cn(isAuthed ? 'border-[#12B76A] bg-[#32D583]' : 'border-gray-400 bg-gray-300', 'rounded h-2 w-2 border')}></div>- <div className='leading-5 text-sm font-medium text-gray-700'>{t(`tools.auth.${isAuthed ? 'authorized' : 'unauthorized'}`)}</div>- </div>- )}-- {collection.type === CollectionType.custom && (- <div- className={cn('cursor-pointer', 'ml-1 shrink-0 flex items-center h-8 border border-gray-200 rounded-lg px-3 space-x-2 shadow-xs')}- onClick={() => onShowEditCustomCollection()}- >- <Settings01 className='w-4 h-4 text-gray-700' />- <div className='leading-5 text-sm font-medium text-gray-700'>{t('tools.createTool.editAction')}</div>- </div>- )}- </div >- )-}-export default React.memo(Header)diff --git a/web/app/components/tools/tool-list/index.tsx b/web/app/components/tools/tool-list/index.tsxdeleted file mode 100644index 9228a028a54..00000000000--- a/web/app/components/tools/tool-list/index.tsx+++ /dev/null@@ -1,220 +0,0 @@-'use client'-import type { FC } from 'react'-import React, { useEffect, useState } from 'react'-import { useTranslation } from 'react-i18next'-import cn from 'classnames'-import { AuthHeaderPrefix, AuthType, CollectionType, LOC } from '../types'-import type { Collection, CustomCollectionBackend, Tool } from '../types'-import Loading from '../../base/loading'-import { ArrowNarrowRight } from '../../base/icons/src/vender/line/arrows'-import Toast from '../../base/toast'-import { ConfigurateMethodEnum } from '../../header/account-setting/model-provider-page/declarations'-import Header from './header'-import Item from './item'-import AppIcon from '@/app/components/base/app-icon'-import ConfigCredential from '@/app/components/tools/setting/build-in/config-credentials'-import { fetchCustomCollection, removeBuiltInToolCredential, removeCustomCollection, updateBuiltInToolCredential, updateCustomCollection } from '@/service/tools'-import EditCustomToolModal from '@/app/components/tools/edit-custom-collection-modal'-import type { AgentTool } from '@/types/app'-import { MAX_TOOLS_NUM } from '@/config'-import { useModalContext } from '@/context/modal-context'-import { useProviderContext } from '@/context/provider-context'--type Props = {- collection: Collection | null- list: Tool[]- // onToolListChange: () => void // custom tools change- loc: LOC- addedTools?: AgentTool[]- onAddTool?: (collection: Collection, payload: Tool) => void- onRefreshData: () => void- onCollectionRemoved: () => void- isLoading: boolean-}--const ToolList: FC<Props> = ({- collection,- list,- loc,- addedTools,- onAddTool,- onRefreshData,- onCollectionRemoved,- isLoading,-}) => {- const { t } = useTranslation()- const isInToolsPage = loc === LOC.tools- const isBuiltIn = collection?.type === CollectionType.builtIn- const isModel = collection?.type === CollectionType.model- const needAuth = collection?.allow_delete-- const { setShowModelModal } = useModalContext()- const [showSettingAuth, setShowSettingAuth] = useState(false)- const { modelProviders: providers } = useProviderContext()- const showSettingAuthModal = () => {- if (isModel) {- const provider = providers.find(item => item.provider === collection?.id)- if (provider) {- setShowModelModal({- payload: {- currentProvider: provider,- currentConfigurateMethod: ConfigurateMethodEnum.predefinedModel,- currentCustomConfigrationModelFixedFields: undefined,- },- onSaveCallback: () => {- onRefreshData()- },- })- }- }- else {- setShowSettingAuth(true)- }- }-- const [customCollection, setCustomCollection] = useState<CustomCollectionBackend | null>(null)- useEffect(() => {- if (!collection)- return- (async () => {- if (collection.type === CollectionType.custom) {- const res = await fetchCustomCollection(collection.name)- if (res.credentials.auth_type === AuthType.apiKey && !res.credentials.api_key_header_prefix) {- if (res.credentials.api_key_value)- res.credentials.api_key_header_prefix = AuthHeaderPrefix.custom- }- setCustomCollection({- ...res,- provider: collection.name,- })- }- })()- }, [collection])- const [isShowEditCollectionToolModal, setIsShowEditCustomCollectionModal] = useState(false)-- const doUpdateCustomToolCollection = async (data: CustomCollectionBackend) => {- await updateCustomCollection(data)- onRefreshData()- Toast.notify({- type: 'success',- message: t('common.api.actionSuccess'),- })- setIsShowEditCustomCollectionModal(false)- }-- const doRemoveCustomToolCollection = async () => {- await removeCustomCollection(collection?.name as string)- onCollectionRemoved()- Toast.notify({- type: 'success',- message: t('common.api.actionSuccess'),- })- setIsShowEditCustomCollectionModal(false)- }-- if (!collection || isLoading)- return <Loading type='app' />-- const icon = <>{typeof collection.icon === 'string'- ? (- <div- className='p-2 bg-cover bg-center border border-gray-100 rounded-lg'- >- <div className='w-6 h-6 bg-center bg-contain rounded-md'- style={{- backgroundImage: `url(${collection.icon})`,- }}- ></div>- </div>- )- : (- <AppIcon- size='large'- icon={collection.icon.content}- background={collection.icon.background}- />- )}- </>-- return (- <div className='flex flex-col h-full pb-4'>- <Header- icon={icon}- collection={collection}- loc={loc}- onShowAuth={() => showSettingAuthModal()}- onShowEditCustomCollection={() => setIsShowEditCustomCollectionModal(true)}- />- <div className={cn(isInToolsPage ? 'px-6 pt-4' : 'px-4 pt-3')}>- <div className='flex items-center h-[4.5] space-x-2 text-xs font-medium text-gray-500'>- <div className=''>{t('tools.includeToolNum', {- num: list.length,- })}</div>- {needAuth && (isBuiltIn || isModel) && !collection.is_team_authorization && (- <>- <div>·</div>- <div- className='flex items-center text-[#155EEF] cursor-pointer'- onClick={() => showSettingAuthModal()}- >- <div>{t('tools.auth.setup')}</div>- <ArrowNarrowRight className='ml-0.5 w-3 h-3' />- </div>- </>- )}- </div>- </div>- <div className={cn(isInToolsPage ? 'px-6' : 'px-4', 'grow h-0 pt-2 overflow-y-auto')}>- {/* list */}- <div className={cn(isInToolsPage ? 'grid-cols-3 gap-4' : 'grid-cols-1 gap-2', 'grid')}>- {list.map(item => (- <Item- key={item.name}- icon={icon}- payload={item}- collection={collection}- isInToolsPage={isInToolsPage}- isToolNumMax={(addedTools?.length || 0) >= MAX_TOOLS_NUM}- added={!!addedTools?.find(v => v.provider_id === collection.id && v.provider_type === collection.type && v.tool_name === item.name)}- onAdd={!isInToolsPage ? tool => onAddTool?.(collection as Collection, tool) : undefined}- />- ))}- </div>- </div>- {showSettingAuth && (- <ConfigCredential- collection={collection}- onCancel={() => setShowSettingAuth(false)}- onSaved={async (value) => {- await updateBuiltInToolCredential(collection.name, value)- Toast.notify({- type: 'success',- message: t('common.api.actionSuccess'),- })- await onRefreshData()- setShowSettingAuth(false)- }}- onRemove={async () => {- await removeBuiltInToolCredential(collection.name)- Toast.notify({- type: 'success',- message: t('common.api.actionSuccess'),- })- await onRefreshData()- setShowSettingAuth(false)- }}- />- )}-- {isShowEditCollectionToolModal && (- <EditCustomToolModal- payload={customCollection}- onHide={() => setIsShowEditCustomCollectionModal(false)}- onEdit={doUpdateCustomToolCollection}- onRemove={doRemoveCustomToolCollection}- />- )}- </div>- )-}-export default React.memo(ToolList)diff --git a/web/app/components/tools/tool-list/item.tsx b/web/app/components/tools/tool-list/item.tsxdeleted file mode 100644index e6e07cd5c7b..00000000000--- a/web/app/components/tools/tool-list/item.tsx+++ /dev/null@@ -1,84 +0,0 @@-'use client'-import type { FC } from 'react'-import React, { useState } from 'react'-import { useContext } from 'use-context-selector'-import cn from 'classnames'-import { useTranslation } from 'react-i18next'-import type { Collection, Tool } from '../types'-import Button from '../../base/button'-import { CollectionType } from '../types'-import TooltipPlus from '../../base/tooltip-plus'-import I18n from '@/context/i18n'-import SettingBuiltInTool from '@/app/components/app/configuration/config/agent/agent-tools/setting-built-in-tool'-import { getLanguage } from '@/i18n/language'-type Props = {- collection: Collection- icon: JSX.Element- payload: Tool- isInToolsPage: boolean- isToolNumMax: boolean- added?: boolean- onAdd?: (payload: Tool) => void-}--const Item: FC<Props> = ({- collection,- icon,- payload,- isInToolsPage,- isToolNumMax,- added,- onAdd,-}) => {- const { t } = useTranslation()- const { locale } = useContext(I18n)- const language = getLanguage(locale)-- const isBuiltIn = collection.type === CollectionType.builtIn- const isModel = collection.type === CollectionType.model- const canShowDetail = isInToolsPage- const [showDetail, setShowDetail] = useState(false)- const addBtn = <Button className='shrink-0 flex items-center h-7 !px-3 !text-xs !font-medium !text-gray-700' disabled={added || !collection.is_team_authorization} onClick={() => onAdd?.(payload)}>{t(`common.operation.${added ? 'added' : 'add'}`)}</Button>-- return (- <>- <div- className={cn(canShowDetail && 'cursor-pointer', 'flex justify-between items-start p-4 rounded-xl border border-gray-200 bg-gray-50 shadow-xs')}- onClick={() => canShowDetail && setShowDetail(true)}- >- <div className='flex items-start w-full'>- {icon}- <div className='ml-3 w-0 grow'>- <div className={cn('text-base font-semibold text-gray-900 truncate')}>{payload.label[language]}</div>- <div className={cn('leading-[18px] text-[13px] font-normal text-gray-500')}>- {payload.description[language]}- </div>- </div>- </div>- <div className='shrink-0'>- {!isToolNumMax && onAdd && (- !collection.is_team_authorization- ? <TooltipPlus popupContent={t('tools.auth.unauthorized')}>- {addBtn}- </TooltipPlus>- : addBtn- )}- </div>- </div>- {showDetail && (- <SettingBuiltInTool- collection={collection}- toolName={payload.name}- readonly- onHide={() => {- setShowDetail(false)- }}- isBuiltIn={isBuiltIn}- isModel={isModel}- />- )}- </>-- )-}-export default React.memo(Item)diff --git a/web/app/components/tools/tool-nav-list/index.tsx b/web/app/components/tools/tool-nav-list/index.tsxdeleted file mode 100644index 3a8fd4088bc..00000000000--- a/web/app/components/tools/tool-nav-list/index.tsx+++ /dev/null@@ -1,28 +0,0 @@-'use client'-import type { FC } from 'react'-import React from 'react'-import cn from 'classnames'-import Item from './item'-import type { Collection } from '@/app/components/tools/types'-type Props = {- className?: string- currentIndex: number- list: Collection[]- onChosen: (index: number) => void-}--const ToolNavList: FC<Props> = ({- className,- currentIndex,- list,- onChosen,-}) => {- return (- <div className={cn(className)}>- {list.map((item, index) => (- <Item isCurrent={index === currentIndex} key={index} payload={item} onClick={() => onChosen(index)}></Item>- ))}- </div>- )-}-export default React.memo(ToolNavList)diff --git a/web/app/components/tools/tool-nav-list/item.tsx b/web/app/components/tools/tool-nav-list/item.tsxdeleted file mode 100644index 2d3606d13e3..00000000000--- a/web/app/components/tools/tool-nav-list/item.tsx+++ /dev/null@@ -1,50 +0,0 @@-'use client'-import type { FC } from 'react'-import React from 'react'-import { useContext } from 'use-context-selector'-import cn from 'classnames'-import AppIcon from '../../base/app-icon'-import type { Collection } from '@/app/components/tools/types'-import I18n from '@/context/i18n'-import { getLanguage } from '@/i18n/language'--type Props = {- isCurrent: boolean- payload: Collection- onClick: () => void-}--const Item: FC<Props> = ({- isCurrent,- payload,- onClick,-}) => {- const { locale } = useContext(I18n)- const language = getLanguage(locale)- return (- <div- className={cn(isCurrent && 'bg-white shadow-xs rounded-lg', 'mt-1 flex h-9 items-center px-2 space-x-2 cursor-pointer')}- onClick={() => !isCurrent && onClick()}- >- {typeof payload.icon === 'string'- ? (- <div- className='w-6 h-6 bg-cover bg-center rounded-md'- style={{- backgroundImage: `url(${payload.icon})`,- }}- ></div>- )- : (- <AppIcon- size='tiny'- icon={payload.icon.content}- background={payload.icon.background}- />- )}- <div className={cn(isCurrent && 'text-primary-600 font-semibold', 'leading-5 text-sm font-normal truncate')}>{payload.label[language]}</div>-- </div>- )-}-export default React.memo(Item)diff --git a/web/app/components/tools/types.ts b/web/app/components/tools/types.tsindex b84afd795be..f2784e9dfe9 100644--- a/web/app/components/tools/types.ts+++ b/web/app/components/tools/types.ts@@ -27,6 +27,7 @@ export enum CollectionType {builtIn = 'builtin',custom = 'api',model = 'model',+ workflow = 'workflow',}export type Emoji = {@@ -45,6 +46,7 @@ export type Collection = {team_credentials: Record<string, any>is_team_authorization: booleanallow_delete: boolean+ labels: string[]}export type ToolParameter = {@@ -52,19 +54,25 @@ export type ToolParameter = {label: TypeWithI18Nhuman_description: TypeWithI18Ntype: string+ form: string+ llm_description: stringrequired: booleandefault: stringoptions?: {label: TypeWithI18Nvalue: string}[]+ min?: number+ max?: number}export type Tool = {name: string+ author: stringlabel: TypeWithI18Ndescription: anyparameters: ToolParameter[]+ labels: string[]}export type ToolCredential = {@@ -91,13 +99,17 @@ export type CustomCollectionBackend = {privacy_policy: stringcustom_disclaimer: stringtools?: ParamItem[]+ id: string+ labels: string[]}export type ParamItem = {name: stringlabel: TypeWithI18Nhuman_description: TypeWithI18N+ llm_description: stringtype: string+ form: stringrequired: booleandefault: stringmin?: number@@ -115,3 +127,39 @@ export type CustomParamSchema = {method: stringparameters: ParamItem[]}++export type WorkflowToolProviderParameter = {+ name: string+ form: string+ description: string+ required?: boolean+ type?: string+}++export type WorkflowToolProviderRequest = {+ name: string+ icon: Emoji+ description: string+ parameters: WorkflowToolProviderParameter[]+ labels: string[]+ privacy_policy: string+}++export type WorkflowToolProviderResponse = {+ workflow_app_id: string+ workflow_tool_id: string+ label: string+ name: string+ icon: Emoji+ description: string+ synced: boolean+ tool: {+ author: string+ name: string+ label: TypeWithI18N+ description: TypeWithI18N+ labels: string[]+ parameters: ParamItem[]+ }+ privacy_policy: string+}diff --git a/web/app/components/tools/workflow-tool/configure-button.tsx b/web/app/components/tools/workflow-tool/configure-button.tsxnew file mode 100644index 00000000000..38e3b869df3--- /dev/null+++ b/web/app/components/tools/workflow-tool/configure-button.tsx@@ -0,0 +1,225 @@+'use client'+import React, { useCallback, useEffect, useMemo, useState } from 'react'+import cn from 'classnames'+import { useTranslation } from 'react-i18next'+import { useRouter } from 'next/navigation'+import Button from '@/app/components/base/button'+import { ArrowUpRight } from '@/app/components/base/icons/src/vender/line/arrows'+import { Tools } from '@/app/components/base/icons/src/vender/line/others'+import Indicator from '@/app/components/header/indicator'+import WorkflowToolModal from '@/app/components/tools/workflow-tool'+import Loading from '@/app/components/base/loading'+import Toast from '@/app/components/base/toast'+import { createWorkflowToolProvider, fetchWorkflowToolDetailByAppID, saveWorkflowToolProvider } from '@/service/tools'+import type { Emoji, WorkflowToolProviderParameter, WorkflowToolProviderRequest, WorkflowToolProviderResponse } from '@/app/components/tools/types'+import type { InputVar } from '@/app/components/workflow/types'++type Props = {+ disabled: boolean+ published: boolean+ detailNeedUpdate: boolean+ workflowAppId: string+ icon: Emoji+ name: string+ description: string+ inputs?: InputVar[]+ handlePublish: () => void+ onRefreshData?: () => void+}++const WorkflowToolConfigureButton = ({+ disabled,+ published,+ detailNeedUpdate,+ workflowAppId,+ icon,+ name,+ description,+ inputs,+ handlePublish,+ onRefreshData,+}: Props) => {+ const { t } = useTranslation()+ const router = useRouter()+ const [showModal, setShowModal] = useState(false)+ const [isLoading, setIsLoading] = useState(false)+ const [detail, setDetail] = useState<WorkflowToolProviderResponse>()++ const outdated = useMemo(() => {+ if (!detail)+ return false+ if (detail.tool.parameters.length !== inputs?.length) {+ return true+ }+ else {+ for (const item of inputs || []) {+ const param = detail.tool.parameters.find(toolParam => toolParam.name === item.variable)+ if (!param) {+ return true+ }+ else if (param.required !== item.required) {+ return true+ }+ else {+ if (item.type === 'paragraph' && param.type !== 'string')+ return true+ if (param.type !== item.type && !(param.type === 'string' && item.type === 'paragraph'))+ return true+ }+ }+ }+ return false+ }, [detail, inputs])++ const payload = useMemo(() => {+ let parameters: WorkflowToolProviderParameter[] = []+ if (!published) {+ parameters = (inputs || []).map((item) => {+ return {+ name: item.variable,+ description: '',+ form: 'llm',+ required: item.required,+ type: item.type,+ }+ })+ }+ else if (detail && detail.tool) {+ parameters = (inputs || []).map((item) => {+ return {+ name: item.variable,+ required: item.required,+ type: item.type === 'paragraph' ? 'string' : item.type,+ description: detail.tool.parameters.find(param => param.name === item.variable)?.llm_description || '',+ form: detail.tool.parameters.find(param => param.name === item.variable)?.form || 'llm',+ }+ })+ }+ return {+ icon: detail?.icon || icon,+ label: detail?.label || name,+ name: detail?.name || '',+ description: detail?.description || description,+ parameters,+ labels: detail?.tool?.labels || [],+ privacy_policy: detail?.privacy_policy || '',+ ...(published+ ? {+ workflow_tool_id: detail?.workflow_tool_id,+ }+ : {+ workflow_app_id: workflowAppId,+ }),+ }+ }, [detail, published, workflowAppId, icon, name, description, inputs])++ const getDetail = useCallback(async (workflowAppId: string) => {+ setIsLoading(true)+ const res = await fetchWorkflowToolDetailByAppID(workflowAppId)+ setDetail(res)+ setIsLoading(false)+ }, [])++ useEffect(() => {+ if (published)+ getDetail(workflowAppId)+ }, [getDetail, published, workflowAppId])++ useEffect(() => {+ if (detailNeedUpdate)+ getDetail(workflowAppId)+ }, [detailNeedUpdate, getDetail, workflowAppId])++ const createHandle = async (data: WorkflowToolProviderRequest & { workflow_app_id: string }) => {+ try {+ await createWorkflowToolProvider(data)+ onRefreshData?.()+ getDetail(workflowAppId)+ Toast.notify({+ type: 'success',+ message: t('common.api.actionSuccess'),+ })+ setShowModal(false)+ }+ catch (e) {+ Toast.notify({ type: 'error', message: (e as Error).message })+ }+ }++ const updateWorkflowToolProvider = async (data: WorkflowToolProviderRequest & Partial<{+ workflow_app_id: string+ workflow_tool_id: string+ }>) => {+ try {+ await handlePublish()+ await saveWorkflowToolProvider(data)+ onRefreshData?.()+ getDetail(workflowAppId)+ Toast.notify({+ type: 'success',+ message: t('common.api.actionSuccess'),+ })+ setShowModal(false)+ }+ catch (e) {+ Toast.notify({ type: 'error', message: (e as Error).message })+ }+ }++ return (+ <>+ <div className='mt-2 pt-2 border-t-[0.5px] border-t-black/5'>+ {(!published || !isLoading) && (+ <div className={cn(+ 'group bg-gray-100 rounded-lg transition-colors',+ disabled ? 'shadow-xs opacity-30 cursor-not-allowed' : 'cursor-pointer',+ !published && 'hover:bg-primary-50',+ )}>+ <div+ className='flex justify-start items-center gap-2 px-2.5 py-2'+ onClick={() => !published && setShowModal(true)}+ >+ <Tools className={cn('relative w-4 h-4', !published && 'group-hover:text-primary-600')}/>+ <div title={t('workflow.common.workflowAsTool') || ''} className={cn('grow shrink basis-0 text-[13px] font-medium leading-[18px] truncate', !published && 'group-hover:text-primary-600')}>{t('workflow.common.workflowAsTool')}</div>+ {!published && (+ <span className='shrink-0 px-1 border border-black/8 rounded-[5px] bg-white text-[10px] font-medium leading-[18px] text-gray-500'>{t('workflow.common.configureRequired').toLocaleUpperCase()}</span>+ )}+ </div>+ {published && (+ <div className='px-2.5 py-2 border-t-[0.5px] border-black/5'>+ <div className='flex justify-between'>+ <Button+ className='px-2 w-[140px] py-0 h-6 shadow-xs rounded-md text-xs font-medium text-gray-700 border-[0.5px] bg-white border-gray-200'+ onClick={() => setShowModal(true)}+ >+ {t('workflow.common.configure')}+ {outdated && <Indicator className='ml-1' color={'yellow'} />}+ </Button>+ <Button+ className='px-2 w-[140px] py-0 h-6 shadow-xs rounded-md text-xs font-medium text-gray-700 border-[0.5px] bg-white border-gray-200'+ onClick={() => router.push('/tools?category=workflow')}+ >+ {t('workflow.common.manageInTools')}+ <ArrowUpRight className='ml-1' />+ </Button>+ </div>+ {outdated && <div className='mt-1 text-xs leading-[18px] text-[#dc6803]'>{t('workflow.common.workflowAsToolTip')}</div>}+ </div>+ )}+ </div>+ )}+ {published && isLoading && <div className='pt-2'><Loading type='app'/></div>}+ </div>+ {showModal && (+ <WorkflowToolModal+ isAdd={!published}+ payload={payload}+ onHide={() => setShowModal(false)}+ onCreate={createHandle}+ onSave={updateWorkflowToolProvider}+ />+ )}+ </>+ )+}+export default WorkflowToolConfigureButtondiff --git a/web/app/components/tools/workflow-tool/confirm-modal/index.tsx b/web/app/components/tools/workflow-tool/confirm-modal/index.tsxnew file mode 100644index 00000000000..04338547e96--- /dev/null+++ b/web/app/components/tools/workflow-tool/confirm-modal/index.tsx@@ -0,0 +1,47 @@+'use client'++import { useTranslation } from 'react-i18next'+import cn from 'classnames'+import s from './style.module.css'+import Button from '@/app/components/base/button'+import Modal from '@/app/components/base/modal'+import { XClose } from '@/app/components/base/icons/src/vender/line/general'+import { AlertTriangle } from '@/app/components/base/icons/src/vender/solid/alertsAndFeedback'++type ConfirmModalProps = {+ show: boolean+ onConfirm?: () => void+ onClose: () => void+}++const ConfirmModal = ({ show, onConfirm, onClose }: ConfirmModalProps) => {+ const { t } = useTranslation()++ return (+ <Modal+ wrapperClassName='!z-[1020]'+ className={cn('p-8 max-w-[600px] w-[600px]', s.bg)}+ isShow={show}+ onClose={() => {}}+ >+ <div className='absolute right-4 top-4 p-2 cursor-pointer' onClick={onClose}>+ <XClose className='w-4 h-4 text-gray-500' />+ </div>+ <div className='w-12 h-12 p-3 bg-white rounded-xl border-[0.5px] border-gray-100 shadow-xl'>+ <AlertTriangle className='w-6 h-6 text-[rgb(247,144,9)]' />+ </div>+ <div className='relative mt-3 text-xl font-semibold leading-[30px] text-gray-900'>{t('tools.createTool.confirmTitle')}</div>+ <div className='my-1 text-gray-500 text-sm leading-5'>+ {t('tools.createTool.confirmTip')}+ </div>+ <div className='pt-6 flex justify-end items-center'>+ <div className='flex items-center'>+ <Button className='mr-2 text-gray-700 text-sm font-medium' onClick={onClose}>{t('common.operation.cancel')}</Button>+ <Button className='text-sm font-medium border-red-700 border-[0.5px]' type="warning" onClick={onConfirm}>{t('common.operation.confirm')}</Button>+ </div>+ </div>+ </Modal>+ )+}++export default ConfirmModaldiff --git a/web/app/components/tools/workflow-tool/confirm-modal/style.module.css b/web/app/components/tools/workflow-tool/confirm-modal/style.module.cssnew file mode 100644index 00000000000..14367ec5759--- /dev/null+++ b/web/app/components/tools/workflow-tool/confirm-modal/style.module.css@@ -0,0 +1,3 @@+.bg {+ background: linear-gradient(180deg, rgba(247, 144, 9, 0.05) 0%, rgba(247, 144, 9, 0.00) 24.41%), #F9FAFB;+}diff --git a/web/app/components/tools/workflow-tool/index.tsx b/web/app/components/tools/workflow-tool/index.tsxnew file mode 100644index 00000000000..6fbcf337692--- /dev/null+++ b/web/app/components/tools/workflow-tool/index.tsx@@ -0,0 +1,282 @@+'use client'+import type { FC } from 'react'+import React, { useState } from 'react'+import { useTranslation } from 'react-i18next'+import cn from 'classnames'+import produce from 'immer'+import type { Emoji, WorkflowToolProviderParameter, WorkflowToolProviderRequest } from '../types'+import Drawer from '@/app/components/base/drawer-plus'+import Button from '@/app/components/base/button'+import Toast from '@/app/components/base/toast'+import EmojiPicker from '@/app/components/base/emoji-picker'+import AppIcon from '@/app/components/base/app-icon'+import MethodSelector from '@/app/components/tools/workflow-tool/method-selector'+import LabelSelector from '@/app/components/tools/labels/selector'+import ConfirmModal from '@/app/components/tools/workflow-tool/confirm-modal'+import { HelpCircle } from '@/app/components/base/icons/src/vender/line/general'+import Tooltip from '@/app/components/base/tooltip'++type Props = {+ isAdd?: boolean+ payload: any+ onHide: () => void+ onRemove?: () => void+ onCreate?: (payload: WorkflowToolProviderRequest & { workflow_app_id: string }) => void+ onSave?: (payload: WorkflowToolProviderRequest & Partial<{+ workflow_app_id: string+ workflow_tool_id: string+ }>) => void+}+// Add and Edit+const WorkflowToolAsModal: FC<Props> = ({+ isAdd,+ payload,+ onHide,+ onRemove,+ onSave,+ onCreate,+}) => {+ const { t } = useTranslation()++ const [showEmojiPicker, setShowEmojiPicker] = useState<Boolean>(false)+ const [emoji, setEmoji] = useState<Emoji>(payload.icon)+ const [label, setLabel] = useState<string>(payload.label)+ const [name, setName] = useState(payload.name)+ const [description, setDescription] = useState(payload.description)+ const [parameters, setParameters] = useState<WorkflowToolProviderParameter[]>(payload.parameters)+ const handleParameterChange = (key: string, value: string, index: number) => {+ const newData = produce(parameters, (draft: WorkflowToolProviderParameter[]) => {+ if (key === 'description')+ draft[index].description = value+ else+ draft[index].form = value+ })+ setParameters(newData)+ }+ const [labels, setLabels] = useState<string[]>(payload.labels)+ const handleLabelSelect = (value: string[]) => {+ setLabels(value)+ }+ const [privacyPolicy, setPrivacyPolicy] = useState(payload.privacy_policy)+ const [showModal, setShowModal] = useState(false)++ const isNameValid = (name: string) => {+ return /^[a-zA-Z0-9_]+$/.test(name)+ }++ const onConfirm = () => {+ if (!label) {+ return Toast.notify({+ type: 'error',+ message: 'Please enter the tool name',+ })+ }+ if (!name) {+ return Toast.notify({+ type: 'error',+ message: 'Please enter the name for tool call',+ })+ }+ else if (!isNameValid(name)) {+ return Toast.notify({+ type: 'error',+ message: 'Name for tool call can only contain numbers, letters, and underscores',+ })+ }+ const requestParams = {+ name,+ description,+ icon: emoji,+ label,+ parameters: parameters.map(item => ({+ name: item.name,+ description: item.description,+ form: item.form,+ })),+ labels,+ privacy_policy: privacyPolicy,+ }+ if (!isAdd) {+ onSave?.({+ ...requestParams,+ workflow_tool_id: payload.workflow_tool_id,+ })+ }+ else {+ onCreate?.({+ ...requestParams,+ workflow_app_id: payload.workflow_app_id,+ })+ }+ }++ return (+ <>+ <Drawer+ isShow+ onHide={onHide}+ title={t('workflow.common.workflowAsTool')!}+ panelClassName='mt-2 !w-[640px]'+ maxWidthClassName='!max-w-[640px]'+ height='calc(100vh - 16px)'+ headerClassName='!border-b-black/5'+ body={+ <div className='flex flex-col h-full'>+ <div className='grow h-0 overflow-y-auto px-6 py-3 space-y-4'>+ {/* name & icon */}+ <div>+ <div className='py-2 leading-5 text-sm font-medium text-gray-900'>{t('tools.createTool.name')}</div>+ <div className='flex items-center justify-between gap-3'>+ <AppIcon size='large' onClick={() => { setShowEmojiPicker(true) }} className='cursor-pointer' icon={emoji.content} background={emoji.background} />+ <input+ type='text'+ className='grow h-10 px-3 text-sm font-normal bg-gray-100 rounded-lg border border-transparent outline-none appearance-none caret-primary-600 placeholder:text-gray-400 hover:bg-gray-50 hover:border hover:border-gray-300 focus:bg-gray-50 focus:border focus:border-gray-300 focus:shadow-xs'+ placeholder={t('tools.createTool.toolNamePlaceHolder')!}+ value={label}+ onChange={e => setLabel(e.target.value)}+ />+ </div>+ </div>+ {/* name for tool call */}+ <div>+ <div className='flex items-center py-2 leading-5 text-sm font-medium text-gray-900'>+ {t('tools.createTool.nameForToolCall')}+ <Tooltip+ htmlContent={+ <div className='w-[180px]'>+ {t('tools.createTool.nameForToolCallPlaceHolder')}+ </div>+ }+ selector='workflow-tool-modal-tooltip'+ >+ <HelpCircle className='ml-2 w-[14px] h-[14px] text-gray-400' />+ </Tooltip>+ </div>+ <input+ type='text'+ className='w-full h-10 px-3 text-sm font-normal bg-gray-100 rounded-lg border border-transparent outline-none appearance-none caret-primary-600 placeholder:text-gray-400 hover:bg-gray-50 hover:border hover:border-gray-300 focus:bg-gray-50 focus:border focus:border-gray-300 focus:shadow-xs'+ placeholder={t('tools.createTool.nameForToolCallPlaceHolder')!}+ value={name}+ onChange={e => setName(e.target.value)}+ />+ {!isNameValid(name) && (+ <div className='text-xs leading-[18px] text-[#DC6803]'>{t('tools.createTool.nameForToolCallTip')}</div>+ )}+ </div>+ {/* description */}+ <div>+ <div className='py-2 leading-5 text-sm font-medium text-gray-900'>{t('tools.createTool.description')}</div>+ <textarea+ className='w-full h-10 px-3 py-2 text-sm font-normal bg-gray-100 rounded-lg border border-transparent outline-none appearance-none caret-primary-600 placeholder:text-gray-400 hover:bg-gray-50 hover:border hover:border-gray-300 focus:bg-gray-50 focus:border focus:border-gray-300 focus:shadow-xs h-[80px] resize-none'+ placeholder={t('tools.createTool.descriptionPlaceholder') || ''}+ value={description}+ onChange={e => setDescription(e.target.value)}+ />+ </div>+ {/* Tool Input */}+ <div>+ <div className='py-2 leading-5 text-sm font-medium text-gray-900'>{t('tools.createTool.toolInput.title')}</div>+ <div className='rounded-lg border border-gray-200 w-full overflow-x-auto'>+ <table className='w-full leading-[18px] text-xs text-gray-700 font-normal'>+ <thead className='text-gray-500 uppercase'>+ <tr className='border-b border-gray-200'>+ <th className="p-2 pl-3 font-medium w-[156px]">{t('tools.createTool.toolInput.name')}</th>+ <th className="p-2 pl-3 font-medium w-[102px]">{t('tools.createTool.toolInput.method')}</th>+ <th className="p-2 pl-3 font-medium">{t('tools.createTool.toolInput.description')}</th>+ </tr>+ </thead>+ <tbody>+ {parameters.map((item, index) => (+ <tr key={index} className='border-b last:border-0 border-gray-200'>+ <td className="p-2 pl-3 max-w-[156px]">+ <div className='text-[13px] leading-[18px]'>+ <div title={item.name} className='flex'>+ <span className='font-medium text-gray-900 truncate'>{item.name}</span>+ <span className='shrink-0 pl-1 text-[#ec4a0a] text-xs leading-[18px]'>{item.required ? t('tools.createTool.toolInput.required') : ''}</span>+ </div>+ <div className='text-gray-500'>{item.type}</div>+ </div>+ </td>+ <td>+ {item.name === '__image' && (+ <div className={cn(+ 'flex items-center gap-1 min-h-[56px] px-3 py-2 h-9 bg-white cursor-default',+ )}>+ <div className={cn('grow text-[13px] leading-[18px] text-gray-700 truncate')}>+ {t('tools.createTool.toolInput.methodParameter')}+ </div>+ </div>+ )}+ {item.name !== '__image' && (+ <MethodSelector value={item.form} onChange={value => handleParameterChange('form', value, index)}/>+ )}+ </td>+ <td className="p-2 pl-3 text-gray-500 w-[236px]">+ <input+ type='text'+ className='grow text-gray-700 text-[13px] leading-[18px] font-normal bg-white outline-none appearance-none caret-primary-600 placeholder:text-gray-300'+ placeholder={t('tools.createTool.toolInput.descriptionPlaceholder')!}+ value={item.description}+ onChange={e => handleParameterChange('description', e.target.value, index)}+ />+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ </div>+ {/* Tags */}+ <div>+ <div className='py-2 leading-5 text-sm font-medium text-gray-900'>{t('tools.createTool.toolInput.label')}</div>+ <LabelSelector value={labels} onChange={handleLabelSelect} />+ </div>+ {/* Privacy Policy */}+ <div>+ <div className='py-2 leading-5 text-sm font-medium text-gray-900'>{t('tools.createTool.privacyPolicy')}</div>+ <input+ value={privacyPolicy}+ onChange={e => setPrivacyPolicy(e.target.value)}+ className='grow w-full h-10 px-3 text-sm font-normal bg-gray-100 rounded-lg border border-transparent outline-none appearance-none caret-primary-600 placeholder:text-gray-400 hover:bg-gray-50 hover:border hover:border-gray-300 focus:bg-gray-50 focus:border focus:border-gray-300 focus:shadow-xs' placeholder={t('tools.createTool.privacyPolicyPlaceholder') || ''} />+ </div>+ </div>+ <div className={cn((!isAdd && onRemove) ? 'justify-between' : 'justify-end', 'mt-2 shrink-0 flex py-4 px-6 rounded-b-[10px] bg-gray-50 border-t border-black/5')} >+ {!isAdd && onRemove && (+ <Button className='flex items-center h-8 !px-3 !text-[13px] font-medium !text-gray-700' onClick={onRemove}>{t('common.operation.remove')}</Button>+ )}+ <div className='flex space-x-2 '>+ <Button className='flex items-center h-8 !px-3 !text-[13px] font-medium !text-gray-700' onClick={onHide}>{t('common.operation.cancel')}</Button>+ <Button disabled={!label || !name || !isNameValid(name)} className='flex items-center h-8 !px-3 !text-[13px] font-medium' type='primary' onClick={() => {+ if (isAdd)+ onConfirm()+ else+ setShowModal(true)+ }}>{t('common.operation.save')}</Button>+ </div>+ </div>+ </div>+ }+ isShowMask={true}+ clickOutsideNotOpen={true}+ />+ {showEmojiPicker && <EmojiPicker+ onSelect={(icon, icon_background) => {+ setEmoji({ content: icon, background: icon_background })+ setShowEmojiPicker(false)+ }}+ onClose={() => {+ setShowEmojiPicker(false)+ }}+ />}+ {showModal && (+ <ConfirmModal+ show={showModal}+ onClose={() => setShowModal(false)}+ onConfirm={onConfirm}+ />+ )}+ </>++ )+}+export default React.memo(WorkflowToolAsModal)diff --git a/web/app/components/tools/workflow-tool/method-selector.tsx b/web/app/components/tools/workflow-tool/method-selector.tsxnew file mode 100644index 00000000000..28a2c4a0031--- /dev/null+++ b/web/app/components/tools/workflow-tool/method-selector.tsx@@ -0,0 +1,77 @@+import type { FC } from 'react'+import { useState } from 'react'+import { useTranslation } from 'react-i18next'+import cn from 'classnames'+import {+ PortalToFollowElem,+ PortalToFollowElemContent,+ PortalToFollowElemTrigger,+} from '@/app/components/base/portal-to-follow-elem'+import { ChevronDown } from '@/app/components/base/icons/src/vender/line/arrows'+import { Check } from '@/app/components/base/icons/src/vender/line/general'++type MethodSelectorProps = {+ value?: string+ onChange: (v: string) => void+}+const MethodSelector: FC<MethodSelectorProps> = ({+ value,+ onChange,+}) => {+ const { t } = useTranslation()+ const [open, setOpen] = useState(false)++ return (+ <PortalToFollowElem+ open={open}+ onOpenChange={setOpen}+ placement='bottom-start'+ offset={4}+ >+ <div className='relative'>+ <PortalToFollowElemTrigger+ onClick={() => setOpen(v => !v)}+ className='block'+ >+ <div className={cn(+ 'flex items-center gap-1 min-h-[56px] px-3 py-2 h-9 bg-white cursor-pointer hover:bg-gray-100',+ open && '!bg-gray-100 hover:bg-gray-100',+ )}>+ <div className={cn('grow text-[13px] leading-[18px] text-gray-700 truncate')}>+ {value === 'llm' ? t('tools.createTool.toolInput.methodParameter') : t('tools.createTool.toolInput.methodSetting')}+ </div>+ <div className='shrink-0 ml-1 text-gray-700 opacity-60'>+ <ChevronDown className='h-4 w-4'/>+ </div>+ </div>+ </PortalToFollowElemTrigger>+ <PortalToFollowElemContent className='z-[1040]'>+ <div className='relative w-[320px] bg-white rounded-lg border-[0.5px] border-gray-200 shadow-lg'>+ <div className='p-1'>+ <div className='pl-3 pr-2 py-2.5 rounded-lg hover:bg-gray-50 cursor-pointer' onClick={() => onChange('llm')}>+ <div className='flex item-center gap-1'>+ <div className='shrink-0 w-4 h-4'>+ {value === 'llm' && <Check className='shrink-0 w-4 h-4 text-primary-600'/>}+ </div>+ <div className='text-[13px] text-gray-700 font-medium leading-[18px]'>{t('tools.createTool.toolInput.methodParameter')}</div>+ </div>+ <div className='pl-5 text-gray-500 text-[13px] leading-[18px]'>{t('tools.createTool.toolInput.methodParameterTip')}</div>+ </div>+ <div className='pl-3 pr-2 py-2.5 rounded-lg hover:bg-gray-50 cursor-pointer' onClick={() => onChange('form')}>+ <div className='flex item-center gap-1'>+ <div className='shrink-0 w-4 h-4'>+ {value === 'form' && <Check className='shrink-0 w-4 h-4 text-primary-600'/>}+ </div>+ <div className='text-[13px] text-gray-700 font-medium leading-[18px]'>{t('tools.createTool.toolInput.methodSetting')}</div>+ </div>+ <div className='pl-5 text-gray-500 text-[13px] leading-[18px]'>{t('tools.createTool.toolInput.methodSettingTip')}</div>+ </div>+ </div>+ </div>+ </PortalToFollowElemContent>+ </div>+ </PortalToFollowElem>+ )+}++export default MethodSelectordiff --git a/web/app/components/workflow/block-icon.tsx b/web/app/components/workflow/block-icon.tsxindex eecf59d2195..64c4dad2dd3 100644--- a/web/app/components/workflow/block-icon.tsx+++ b/web/app/components/workflow/block-icon.tsx@@ -8,8 +8,10 @@ import {Home,Http,IfElse,+ Iteration,KnowledgeRetrieval,Llm,+ ParameterExtractor,QuestionClassifier,TemplatingTransform,VariableX,@@ -40,7 +42,10 @@ const getIcon = (type: BlockEnum, className: string) => {[BlockEnum.QuestionClassifier]: <QuestionClassifier className={className} />,[BlockEnum.TemplateTransform]: <TemplatingTransform className={className} />,[BlockEnum.VariableAssigner]: <VariableX className={className} />,+ [BlockEnum.VariableAggregator]: <VariableX className={className} />,[BlockEnum.Tool]: <VariableX className={className} />,+ [BlockEnum.Iteration]: <Iteration className={className} />,+ [BlockEnum.ParameterExtractor]: <ParameterExtractor className={className} />,}[type]}const ICON_CONTAINER_BG_COLOR_MAP: Record<string, string> = {@@ -49,12 +54,15 @@ const ICON_CONTAINER_BG_COLOR_MAP: Record<string, string> = {[BlockEnum.Code]: 'bg-[#2E90FA]',[BlockEnum.End]: 'bg-[#F79009]',[BlockEnum.IfElse]: 'bg-[#06AED4]',+ [BlockEnum.Iteration]: 'bg-[#06AED4]',[BlockEnum.HttpRequest]: 'bg-[#875BF7]',[BlockEnum.Answer]: 'bg-[#F79009]',[BlockEnum.KnowledgeRetrieval]: 'bg-[#16B364]',[BlockEnum.QuestionClassifier]: 'bg-[#16B364]',[BlockEnum.TemplateTransform]: 'bg-[#2E90FA]',[BlockEnum.VariableAssigner]: 'bg-[#2E90FA]',+ [BlockEnum.VariableAggregator]: 'bg-[#2E90FA]',+ [BlockEnum.ParameterExtractor]: 'bg-[#2E90FA]',}const BlockIcon: FC<BlockIconProps> = ({type,diff --git a/web/app/components/workflow/block-selector/all-tools.tsx b/web/app/components/workflow/block-selector/all-tools.tsxnew file mode 100644index 00000000000..7a72d59bf12--- /dev/null+++ b/web/app/components/workflow/block-selector/all-tools.tsx@@ -0,0 +1,76 @@+import {+ useMemo,+ useState,+} from 'react'+import cn from 'classnames'+import type {+ OnSelectBlock,+ ToolWithProvider,+} from '../types'+import { useStore } from '../store'+import { ToolTypeEnum } from './types'+import Tools from './tools'+import { useToolTabs } from './hooks'+import { useGetLanguage } from '@/context/i18n'++type AllToolsProps = {+ searchText: string+ onSelect: OnSelectBlock+}+const AllTools = ({+ searchText,+ onSelect,+}: AllToolsProps) => {+ const language = useGetLanguage()+ const tabs = useToolTabs()+ const [activeTab, setActiveTab] = useState(ToolTypeEnum.All)+ const buildInTools = useStore(s => s.buildInTools)+ const customTools = useStore(s => s.customTools)+ const workflowTools = useStore(s => s.workflowTools)++ const tools = useMemo(() => {+ let mergedTools: ToolWithProvider[] = []+ if (activeTab === ToolTypeEnum.All)+ mergedTools = [...buildInTools, ...customTools]+ if (activeTab === ToolTypeEnum.BuiltIn)+ mergedTools = buildInTools+ if (activeTab === ToolTypeEnum.Custom)+ mergedTools = customTools+ if (activeTab === ToolTypeEnum.Workflow)+ mergedTools = workflowTools++ return mergedTools.filter((toolWithProvider) => {+ return toolWithProvider.tools.some((tool) => {+ return tool.label[language].toLowerCase().includes(searchText.toLowerCase())+ })+ })+ }, [activeTab, buildInTools, customTools, workflowTools, searchText, language])+ return (+ <div>+ <div className='flex items-center px-3 h-8 space-x-1 bg-gray-25 border-b-[0.5px] border-black/[0.08] shadow-xs'>+ {+ tabs.map(tab => (+ <div+ className={cn(+ 'flex items-center px-2 h-6 rounded-md hover:bg-gray-100 cursor-pointer',+ 'text-xs font-medium text-gray-700',+ activeTab === tab.key && 'bg-gray-200',+ )}+ key={tab.key}+ onClick={() => setActiveTab(tab.key)}+ >+ {tab.name}+ </div>+ ))+ }+ </div>+ <Tools+ showWorkflowEmpty={activeTab === ToolTypeEnum.Workflow}+ tools={tools}+ onSelect={onSelect}+ />+ </div>+ )+}++export default AllToolsdiff --git a/web/app/components/workflow/block-selector/constants.tsx b/web/app/components/workflow/block-selector/constants.tsxindex 92719f943f7..517d9356f2e 100644--- a/web/app/components/workflow/block-selector/constants.tsx+++ b/web/app/components/workflow/block-selector/constants.tsx@@ -39,6 +39,11 @@ export const BLOCKS: Block[] = [type: BlockEnum.IfElse,title: 'IF/ELSE',},+ {+ classification: BlockClassificationEnum.Logic,+ type: BlockEnum.Iteration,+ title: 'Iteration',+ },{classification: BlockClassificationEnum.Transform,type: BlockEnum.Code,@@ -51,8 +56,13 @@ export const BLOCKS: Block[] = [},{classification: BlockClassificationEnum.Transform,- type: BlockEnum.VariableAssigner,- title: 'Variable Assigner',+ type: BlockEnum.VariableAggregator,+ title: 'Variable Aggregator',+ },+ {+ classification: BlockClassificationEnum.Transform,+ type: BlockEnum.ParameterExtractor,+ title: 'Parameter Extractor',},{classification: BlockClassificationEnum.Utilities,diff --git a/web/app/components/workflow/block-selector/hooks.ts b/web/app/components/workflow/block-selector/hooks.tsindex 38391793d8a..592954afa32 100644--- a/web/app/components/workflow/block-selector/hooks.ts+++ b/web/app/components/workflow/block-selector/hooks.ts@@ -1,6 +1,9 @@import { useTranslation } from 'react-i18next'import { BLOCKS } from './constants'-import { TabsEnum } from './types'+import {+ TabsEnum,+ ToolTypeEnum,+} from './types'export const useBlocks = () => {const { t } = useTranslation()@@ -22,12 +25,31 @@ export const useTabs = () => {name: t('workflow.tabs.blocks'),},{- key: TabsEnum.BuiltInTool,+ key: TabsEnum.Tools,+ name: t('workflow.tabs.tools'),+ },+ ]+}++export const useToolTabs = () => {+ const { t } = useTranslation()++ return [+ {+ key: ToolTypeEnum.All,+ name: t('workflow.tabs.allTool'),+ },+ {+ key: ToolTypeEnum.BuiltIn,name: t('workflow.tabs.builtInTool'),},{- key: TabsEnum.CustomTool,+ key: ToolTypeEnum.Custom,name: t('workflow.tabs.customTool'),},+ {+ key: ToolTypeEnum.Workflow,+ name: t('workflow.tabs.workflowTool'),+ },]}diff --git a/web/app/components/workflow/block-selector/index.tsx b/web/app/components/workflow/block-selector/index.tsxindex efb38818615..bcf96b50454 100644--- a/web/app/components/workflow/block-selector/index.tsx+++ b/web/app/components/workflow/block-selector/index.tsx@@ -39,6 +39,7 @@ type NodeSelectorProps = {asChild?: booleanavailableBlocksTypes?: BlockEnum[]disabled?: boolean+ noBlocks?: boolean}const NodeSelector: FC<NodeSelectorProps> = ({open: openFromProps,@@ -54,6 +55,7 @@ const NodeSelector: FC<NodeSelectorProps> = ({asChild,availableBlocksTypes,disabled,+ noBlocks = false,}) => {const { t } = useTranslation()const [searchText, setSearchText] = useState('')@@ -136,6 +138,7 @@ const NodeSelector: FC<NodeSelectorProps> = ({onSelect={handleSelect}searchText={searchText}availableBlocksTypes={availableBlocksTypes}+ noBlocks={noBlocks}/></div></PortalToFollowElemContent>diff --git a/web/app/components/workflow/block-selector/tabs.tsx b/web/app/components/workflow/block-selector/tabs.tsxindex e717461c1ca..fa798326c75 100644--- a/web/app/components/workflow/block-selector/tabs.tsx+++ b/web/app/components/workflow/block-selector/tabs.tsx@@ -3,67 +3,65 @@ import {memo,useState,} from 'react'+import cn from 'classnames'import type { BlockEnum } from '../types'import { useTabs } from './hooks'import type { ToolDefaultValue } from './types'import { TabsEnum } from './types'-import Tools from './tools'import Blocks from './blocks'+import AllTools from './all-tools'export type TabsProps = {searchText: stringonSelect: (type: BlockEnum, tool?: ToolDefaultValue) => voidavailableBlocksTypes?: BlockEnum[]+ noBlocks?: boolean}const Tabs: FC<TabsProps> = ({searchText,onSelect,availableBlocksTypes,+ noBlocks,}) => {const tabs = useTabs()- const [activeTab, setActiveTab] = useState(tabs[0].key)+ const [activeTab, setActiveTab] = useState(noBlocks ? TabsEnum.Tools : TabsEnum.Blocks)return (<div onClick={e => e.stopPropagation()}>- <div className='flex items-center px-3 border-b-[0.5px] border-b-black/5'>- {- tabs.map(tab => (- <div- key={tab.key}- className={`- relative mr-4 h-[34px] leading-[34px] text-[13px] font-medium cursor-pointer- ${activeTab === tab.key- ? 'text-gray-700 after:absolute after:bottom-0 after:left-0 after:h-0.5 after:w-full after:bg-primary-600'- : 'text-gray-500'}- `}- onClick={() => setActiveTab(tab.key)}- >- {tab.name}- </div>- ))- }- </div>{- activeTab === TabsEnum.Blocks && (- <Blocks- searchText={searchText}- onSelect={onSelect}- availableBlocksTypes={availableBlocksTypes}- />+ !noBlocks && (+ <div className='flex items-center px-3 border-b-[0.5px] border-b-black/5'>+ {+ tabs.map(tab => (+ <div+ key={tab.key}+ className={cn(+ 'relative mr-4 h-[34px] leading-[34px] text-[13px] font-medium cursor-pointer',+ activeTab === tab.key+ ? 'text-gray-700 after:absolute after:bottom-0 after:left-0 after:h-0.5 after:w-full after:bg-primary-600'+ : 'text-gray-500',+ )}+ onClick={() => setActiveTab(tab.key)}+ >+ {tab.name}+ </div>+ ))+ }+ </div>)}{- activeTab === TabsEnum.BuiltInTool && (- <Tools- onSelect={onSelect}+ activeTab === TabsEnum.Blocks && !noBlocks && (+ <BlockssearchText={searchText}+ onSelect={onSelect}+ availableBlocksTypes={availableBlocksTypes}/>)}{- activeTab === TabsEnum.CustomTool && (- <Tools- isCustom+ activeTab === TabsEnum.Tools && (+ <AllToolssearchText={searchText}onSelect={onSelect}/>diff --git a/web/app/components/workflow/block-selector/tools.tsx b/web/app/components/workflow/block-selector/tools.tsxindex 285631d41e7..46e02be646e 100644--- a/web/app/components/workflow/block-selector/tools.tsx+++ b/web/app/components/workflow/block-selector/tools.tsx@@ -1,41 +1,28 @@import {memo,useCallback,- useMemo,} from 'react'import { useTranslation } from 'react-i18next'import BlockIcon from '../block-icon'import { BlockEnum } from '../types'import type { ToolWithProvider } from '../types'-import { useStore } from '../store'import type { ToolDefaultValue } from './types'import Tooltip from '@/app/components/base/tooltip'+import Empty from '@/app/components/tools/add-tool-modal/empty'import { useGetLanguage } from '@/context/i18n'type ToolsProps = {- isCustom?: boolean+ showWorkflowEmpty: booleanonSelect: (type: BlockEnum, tool?: ToolDefaultValue) => void- searchText: string+ tools: ToolWithProvider[]}const Blocks = ({- isCustom,- searchText,+ showWorkflowEmpty,onSelect,+ tools,}: ToolsProps) => {const { t } = useTranslation()const language = useGetLanguage()- const buildInTools = useStore(s => s.buildInTools)- const customTools = useStore(s => s.customTools)-- const tools = useMemo(() => {- const currentTools = isCustom ? customTools : buildInTools-- return currentTools.filter((toolWithProvider) => {- return toolWithProvider.tools.some((tool) => {- return tool.label[language].toLowerCase().includes(searchText.toLowerCase())- })- })- }, [isCustom, customTools, buildInTools, searchText, language])const renderGroup = useCallback((toolWithProvider: ToolWithProvider) => {const list = toolWithProvider.tools@@ -97,10 +84,15 @@ const Blocks = ({return (<div className='p-1 max-w-[320px] max-h-[464px] overflow-y-auto'>{- !tools.length && (+ !tools.length && !showWorkflowEmpty && (<div className='flex items-center px-3 h-[22px] text-xs font-medium text-gray-500'>{t('workflow.tabs.noResult')}</div>)}+ {!tools.length && showWorkflowEmpty && (+ <div className='py-10'>+ <Empty/>+ </div>+ )}{!!tools.length && tools.map(renderGroup)}diff --git a/web/app/components/workflow/block-selector/types.ts b/web/app/components/workflow/block-selector/types.tsindex 9555cf164c9..affa2488b94 100644--- a/web/app/components/workflow/block-selector/types.ts+++ b/web/app/components/workflow/block-selector/types.ts@@ -1,7 +1,13 @@export enum TabsEnum {Blocks = 'blocks',- BuiltInTool = 'built-in-tool',- CustomTool = 'custom-tool',+ Tools = 'tools',+}++export enum ToolTypeEnum {+ All = 'all',+ BuiltIn = 'built-in',+ Custom = 'custom',+ Workflow = 'workflow',}export enum BlockClassificationEnum {diff --git a/web/app/components/workflow/constants.ts b/web/app/components/workflow/constants.tsindex 2b163008ad9..918649a26bb 100644--- a/web/app/components/workflow/constants.ts+++ b/web/app/components/workflow/constants.ts@@ -9,9 +9,11 @@ import IfElseDefault from './nodes/if-else/default'import CodeDefault from './nodes/code/default'import TemplateTransformDefault from './nodes/template-transform/default'import HttpRequestDefault from './nodes/http/default'+import ParameterExtractorDefault from './nodes/parameter-extractor/default'import ToolDefault from './nodes/tool/default'import VariableAssignerDefault from './nodes/variable-assigner/default'import EndNodeDefault from './nodes/end/default'+import IterationDefault from './nodes/iteration/default'type NodesExtraData = {author: string@@ -77,6 +79,15 @@ export const NODES_EXTRA_DATA: Record<BlockEnum, NodesExtraData> = {getAvailableNextNodes: IfElseDefault.getAvailableNextNodes,checkValid: IfElseDefault.checkValid,},+ [BlockEnum.Iteration]: {+ author: 'Dify',+ about: '',+ availablePrevNodes: [],+ availableNextNodes: [],+ getAvailablePrevNodes: IterationDefault.getAvailablePrevNodes,+ getAvailableNextNodes: IterationDefault.getAvailableNextNodes,+ checkValid: IterationDefault.checkValid,+ },[BlockEnum.Code]: {author: 'Dify',about: '',@@ -122,6 +133,24 @@ export const NODES_EXTRA_DATA: Record<BlockEnum, NodesExtraData> = {getAvailableNextNodes: VariableAssignerDefault.getAvailableNextNodes,checkValid: VariableAssignerDefault.checkValid,},+ [BlockEnum.VariableAggregator]: {+ author: 'Dify',+ about: '',+ availablePrevNodes: [],+ availableNextNodes: [],+ getAvailablePrevNodes: VariableAssignerDefault.getAvailablePrevNodes,+ getAvailableNextNodes: VariableAssignerDefault.getAvailableNextNodes,+ checkValid: VariableAssignerDefault.checkValid,+ },+ [BlockEnum.ParameterExtractor]: {+ author: 'Dify',+ about: '',+ availablePrevNodes: [],+ availableNextNodes: [],+ getAvailablePrevNodes: ParameterExtractorDefault.getAvailablePrevNodes,+ getAvailableNextNodes: ParameterExtractorDefault.getAvailableNextNodes,+ checkValid: ParameterExtractorDefault.checkValid,+ },[BlockEnum.Tool]: {author: 'Dify',about: '',@@ -177,6 +206,12 @@ export const NODES_INITIAL_DATA = {desc: '',...IfElseDefault.defaultValue,},+ [BlockEnum.Iteration]: {+ type: BlockEnum.Iteration,+ title: '',+ desc: '',+ ...IterationDefault.defaultValue,+ },[BlockEnum.Code]: {type: BlockEnum.Code,title: '',@@ -210,6 +245,13 @@ export const NODES_INITIAL_DATA = {variables: [],...HttpRequestDefault.defaultValue,},+ [BlockEnum.ParameterExtractor]: {+ type: BlockEnum.ParameterExtractor,+ title: '',+ desc: '',+ variables: [],+ ...ParameterExtractorDefault.defaultValue,+ },[BlockEnum.VariableAssigner]: {type: BlockEnum.VariableAssigner,title: '',@@ -218,6 +260,14 @@ export const NODES_INITIAL_DATA = {output_type: '',...VariableAssignerDefault.defaultValue,},+ [BlockEnum.VariableAggregator]: {+ type: BlockEnum.VariableAggregator,+ title: '',+ desc: '',+ variables: [],+ output_type: '',+ ...VariableAssignerDefault.defaultValue,+ },[BlockEnum.Tool]: {type: BlockEnum.Tool,title: '',@@ -236,6 +286,14 @@ export const AUTO_LAYOUT_OFFSET = {x: -42,y: 243,}+export const ITERATION_NODE_Z_INDEX = 1+export const ITERATION_CHILDREN_Z_INDEX = 1002+export const ITERATION_PADDING = {+ top: 85,+ right: 16,+ bottom: 20,+ left: 16,+}export const RETRIEVAL_OUTPUT_STRUCT = `{"content": "",@@ -259,7 +317,8 @@ export const RETRIEVAL_OUTPUT_STRUCT = `{export const SUPPORT_OUTPUT_VARS_NODE = [BlockEnum.Start, BlockEnum.LLM, BlockEnum.KnowledgeRetrieval, BlockEnum.Code, BlockEnum.TemplateTransform,- BlockEnum.HttpRequest, BlockEnum.Tool, BlockEnum.VariableAssigner, BlockEnum.QuestionClassifier,+ BlockEnum.HttpRequest, BlockEnum.Tool, BlockEnum.VariableAssigner, BlockEnum.VariableAggregator, BlockEnum.QuestionClassifier,+ BlockEnum.ParameterExtractor, BlockEnum.Iteration,]export const LLM_OUTPUT_STRUCT: Var[] = [@@ -320,4 +379,15 @@ export const TOOL_OUTPUT_STRUCT: Var[] = [},]+export const PARAMETER_EXTRACTOR_COMMON_STRUCT: Var[] = [+ {+ variable: '__is_success',+ type: VarType.number,+ },+ {+ variable: '__reason',+ type: VarType.string,+ },+]+export const WORKFLOW_DATA_UPDATE = 'WORKFLOW_DATA_UPDATE'diff --git a/web/app/components/workflow/custom-edge.tsx b/web/app/components/workflow/custom-edge.tsxindex 072aad8d542..c1133955711 100644--- a/web/app/components/workflow/custom-edge.tsx+++ b/web/app/components/workflow/custom-edge.tsx@@ -3,6 +3,7 @@ import {useCallback,useState,} from 'react'+import cn from 'classnames'import { intersection } from 'lodash-es'import type { EdgeProps } from 'reactflow'import {@@ -12,7 +13,7 @@ import {getBezierPath,} from 'reactflow'import {- useNodesExtraData,+ useAvailableBlocks,useNodesInteractions,} from './hooks'import BlockSelector from './block-selector'@@ -20,6 +21,7 @@ import type {Edge,OnSelectBlock,} from './types'+import { ITERATION_CHILDREN_Z_INDEX } from './constants'const CustomEdge = ({id,@@ -49,9 +51,9 @@ const CustomEdge = ({})const [open, setOpen] = useState(false)const { handleNodeAdd } = useNodesInteractions()- const nodesExtraData = useNodesExtraData()- const availablePrevNodes = nodesExtraData[(data as Edge['data'])!.targetType]?.availablePrevNodes || []- const availableNextNodes = nodesExtraData[(data as Edge['data'])!.sourceType]?.availableNextNodes || []+ const { availablePrevBlocks } = useAvailableBlocks((data as Edge['data'])!.targetType, (data as Edge['data'])?.isInIteration)+ const { availableNextBlocks } = useAvailableBlocks((data as Edge['data'])!.sourceType, (data as Edge['data'])?.isInIteration)+const handleOpenChange = useCallback((v: boolean) => {setOpen(v)}, [])@@ -83,11 +85,12 @@ const CustomEdge = ({/><EdgeLabelRenderer><div- className={`- nopan nodrag hover:scale-125- ${data?._hovering ? 'block' : 'hidden'}- ${open && '!block'}- `}+ className={cn(+ 'nopan nodrag hover:scale-125',+ data?._hovering ? 'block' : 'hidden',+ open && '!block',+ data.isInIteration && `z-[${ITERATION_CHILDREN_Z_INDEX}]`,+ )}style={{position: 'absolute',transform: `translate(-50%, -50%) translate(${labelX}px, ${labelY}px)`,@@ -99,7 +102,7 @@ const CustomEdge = ({onOpenChange={handleOpenChange}asChildonSelect={handleInsert}- availableBlocksTypes={intersection(availablePrevNodes, availableNextNodes)}+ availableBlocksTypes={intersection(availablePrevBlocks, availableNextBlocks)}triggerClassName={() => 'hover:scale-150 transition-all'}/></div>diff --git a/web/app/components/workflow/header/index.tsx b/web/app/components/workflow/header/index.tsxindex 7340aa6e50f..679b6e626c2 100644--- a/web/app/components/workflow/header/index.tsx+++ b/web/app/components/workflow/header/index.tsx@@ -2,13 +2,20 @@ import type { FC } from 'react'import {memo,useCallback,+ useMemo,} from 'react'+import { useNodes } from 'reactflow'import { useTranslation } from 'react-i18next'import { useContext } from 'use-context-selector'import {useStore,useWorkflowStore,} from '../store'+import {+ BlockEnum,+ InputVarType,+} from '../types'+import type { StartNodeType } from '../nodes/start/types'import {useChecklistBeforePublish,useNodesReadOnly,@@ -29,6 +36,7 @@ import Button from '@/app/components/base/button'import { useStore as useAppStore } from '@/app/components/app/store'import { publishWorkflow } from '@/service/workflow'import { ArrowNarrowLeft } from '@/app/components/base/icons/src/vender/line/arrows'+import { useFeatures } from '@/app/components/base/features/hooks'const Header: FC = () => {const { t } = useTranslation()@@ -42,6 +50,28 @@ const Header: FC = () => {} = useNodesReadOnly()const publishedAt = useStore(s => s.publishedAt)const draftUpdatedAt = useStore(s => s.draftUpdatedAt)+ const toolPublished = useStore(s => s.toolPublished)+ const nodes = useNodes<StartNodeType>()+ const startNode = nodes.find(node => node.data.type === BlockEnum.Start)+ const startVariables = startNode?.data.variables+ const fileSettings = useFeatures(s => s.features.file)+ const variables = useMemo(() => {+ const data = startVariables || []+ if (fileSettings?.image?.enabled) {+ return [+ ...data,+ {+ type: InputVarType.files,+ variable: '__image',+ required: false,+ label: 'files',+ },+ ]+ }++ return data+ }, [fileSettings?.image?.enabled, startVariables])+const {handleLoadBackupDraft,handleBackupDraft,@@ -108,6 +138,10 @@ const Header: FC = () => {workflowStore.setState({ historyWorkflowData: undefined })}, [workflowStore, handleLoadBackupDraft])+ const handleToolConfigureUpdate = useCallback(() => {+ workflowStore.setState({ toolPublished: true })+ }, [workflowStore])+return (<divclassName='absolute top-0 left-0 z-10 flex items-center justify-between w-full px-3 h-14'@@ -152,6 +186,9 @@ const Header: FC = () => {publishedAt,draftUpdatedAt,disabled: Boolean(getNodesReadOnly()),+ toolPublished,+ inputs: variables,+ onRefreshData: handleToolConfigureUpdate,onPublish,onRestore: onStartRestoring,onToggle: onPublisherToggle,diff --git a/web/app/components/workflow/hooks/index.ts b/web/app/components/workflow/hooks/index.tsindex 44f5464e411..41fb7845a64 100644--- a/web/app/components/workflow/hooks/index.ts+++ b/web/app/components/workflow/hooks/index.ts@@ -12,3 +12,4 @@ export * from './use-workflow-interactions'export * from './use-selection-interactions'export * from './use-panel-interactions'export * from './use-workflow-start-run'+export * from './use-nodes-layout'diff --git a/web/app/components/workflow/hooks/use-checklist.ts b/web/app/components/workflow/hooks/use-checklist.tsindex 0e8d324daf4..818505d0fe4 100644--- a/web/app/components/workflow/hooks/use-checklist.ts+++ b/web/app/components/workflow/hooks/use-checklist.ts@@ -29,6 +29,7 @@ export const useChecklist = (nodes: Node[], edges: Edge[]) => {const isChatMode = useIsChatMode()const buildInTools = useStore(s => s.buildInTools)const customTools = useStore(s => s.customTools)+ const workflowTools = useStore(s => s.workflowTools)const needWarningNodes = useMemo(() => {const list = []@@ -41,14 +42,16 @@ export const useChecklist = (nodes: Node[], edges: Edge[]) => {if (node.data.type === BlockEnum.Tool) {const { provider_type } = node.data- const isBuiltIn = provider_type === CollectionType.builtIn- moreDataForCheckValid = getToolCheckParams(node.data as ToolNodeType, buildInTools, customTools, language)- if (isBuiltIn)+ moreDataForCheckValid = getToolCheckParams(node.data as ToolNodeType, buildInTools, customTools, workflowTools, language)+ if (provider_type === CollectionType.builtIn)toolIcon = buildInTools.find(tool => tool.id === node.data.provider_id)?.icon- if (!isBuiltIn)+ if (provider_type === CollectionType.custom)toolIcon = customTools.find(tool => tool.id === node.data.provider_id)?.icon++ if (provider_type === CollectionType.workflow)+ toolIcon = workflowTools.find(tool => tool.id === node.data.provider_id)?.icon}const { errorMessage } = nodesExtraData[node.data.type].checkValid(node.data, t, moreDataForCheckValid)@@ -83,7 +86,7 @@ export const useChecklist = (nodes: Node[], edges: Edge[]) => {}return list- }, [t, nodes, edges, nodesExtraData, buildInTools, customTools, language, isChatMode])+ }, [t, nodes, edges, nodesExtraData, buildInTools, customTools, workflowTools, language, isChatMode])return needWarningNodes}@@ -93,6 +96,7 @@ export const useChecklistBeforePublish = () => {const language = useGetLanguage()const buildInTools = useStore(s => s.buildInTools)const customTools = useStore(s => s.customTools)+ const workflowTools = useStore(s => s.workflowTools)const { notify } = useToastContext()const isChatMode = useIsChatMode()const store = useStoreApi()@@ -118,7 +122,7 @@ export const useChecklistBeforePublish = () => {const node = nodes[i]let moreDataForCheckValidif (node.data.type === BlockEnum.Tool)- moreDataForCheckValid = getToolCheckParams(node.data as ToolNodeType, buildInTools, customTools, language)+ moreDataForCheckValid = getToolCheckParams(node.data as ToolNodeType, buildInTools, customTools, workflowTools, language)const { errorMessage } = nodesExtraData[node.data.type as BlockEnum].checkValid(node.data, t, moreDataForCheckValid)@@ -144,7 +148,7 @@ export const useChecklistBeforePublish = () => {}return true- }, [nodesExtraData, notify, t, store, isChatMode, buildInTools, customTools, language])+ }, [nodesExtraData, notify, t, store, isChatMode, buildInTools, customTools, workflowTools, language])return {handleCheckBeforePublish,diff --git a/web/app/components/workflow/hooks/use-edges-interactions.ts b/web/app/components/workflow/hooks/use-edges-interactions.tsindex 9070af182ce..e7544c2ab57 100644--- a/web/app/components/workflow/hooks/use-edges-interactions.ts+++ b/web/app/components/workflow/hooks/use-edges-interactions.ts@@ -5,14 +5,11 @@ import type {OnEdgesChange,} from 'reactflow'import {- getConnectedEdges,useStoreApi,} from 'reactflow'import type {- Edge,Node,} from '../types'-import { BlockEnum } from '../types'import { getNodesConnectedSourceOrTargetHandleIdsMap } from '../utils'import { useNodesSyncDraft } from './use-nodes-sync-draft'import { useNodesReadOnly } from './use-workflow'@@ -146,61 +143,6 @@ export const useEdgesInteractions = () => {setEdges(newEdges)}, [store, getNodesReadOnly])- const handleVariableAssignerEdgesChange = useCallback((nodeId: string, variables: any) => {- const {- getNodes,- setNodes,- edges,- setEdges,- } = store.getState()- const nodes = getNodes()- const newEdgesTargetHandleIds = variables.map((item: any) => item[0])- const connectedEdges = getConnectedEdges([{ id: nodeId } as Node], edges).filter(edge => edge.target === nodeId)- const needDeleteEdges = connectedEdges.filter(edge => !newEdgesTargetHandleIds.includes(edge.targetHandle))- const needAddEdgesTargetHandleIds = newEdgesTargetHandleIds.filter((targetHandle: string) => !connectedEdges.some(edge => edge.targetHandle === targetHandle))- const needAddEdges = needAddEdgesTargetHandleIds.map((targetHandle: string) => {- return {- id: `${targetHandle}-${nodeId}`,- type: 'custom',- source: targetHandle,- sourceHandle: 'source',- target: nodeId,- targetHandle,- data: {- sourceType: nodes.find(node => node.id === targetHandle)?.data.type,- targetType: BlockEnum.VariableAssigner,- },- }- })-- const nodesConnectedSourceOrTargetHandleIdsMap = getNodesConnectedSourceOrTargetHandleIdsMap(- [- ...needDeleteEdges.map(edge => ({ type: 'remove', edge })),- ...needAddEdges.map((edge: Edge) => ({ type: 'add', edge })),- ],- nodes,- )- const newNodes = produce(nodes, (draft) => {- draft.forEach((node) => {- if (nodesConnectedSourceOrTargetHandleIdsMap[node.id]) {- node.data = {- ...node.data,- ...nodesConnectedSourceOrTargetHandleIdsMap[node.id],- }- }- })- })- setNodes(newNodes)- const newEdges = produce(edges, (draft) => {- const filtered = draft.filter(edge => !needDeleteEdges.map(needDeleteEdge => needDeleteEdge.id).includes(edge.id))-- filtered.push(...needAddEdges)-- return filtered- })- setEdges(newEdges)- }, [store])-const handleEdgeCancelRunningStatus = useCallback(() => {const {edges,@@ -221,7 +163,6 @@ export const useEdgesInteractions = () => {handleEdgeDeleteByDeleteBranch,handleEdgeDelete,handleEdgesChange,- handleVariableAssignerEdgesChange,handleEdgeCancelRunningStatus,}}diff --git a/web/app/components/workflow/hooks/use-helpline.ts b/web/app/components/workflow/hooks/use-helpline.tsnew file mode 100644index 00000000000..e9dc08c7067--- /dev/null+++ b/web/app/components/workflow/hooks/use-helpline.ts@@ -0,0 +1,114 @@+import { useCallback } from 'react'+import { useStoreApi } from 'reactflow'+import type { Node } from '../types'+import { useWorkflowStore } from '../store'++export const useHelpline = () => {+ const store = useStoreApi()+ const workflowStore = useWorkflowStore()++ const handleSetHelpline = useCallback((node: Node) => {+ const { getNodes } = store.getState()+ const nodes = getNodes()+ const {+ setHelpLineHorizontal,+ setHelpLineVertical,+ } = workflowStore.getState()++ if (node.data.isInIteration) {+ return {+ showHorizontalHelpLineNodes: [],+ showVerticalHelpLineNodes: [],+ }+ }+ const showHorizontalHelpLineNodes = nodes.filter((n) => {+ if (n.id === node.id)+ return false++ if (n.data.isInIteration)+ return false++ const nY = Math.ceil(n.position.y)+ const nodeY = Math.ceil(node.position.y)++ if (nY - nodeY < 5 && nY - nodeY > -5)+ return true++ return false+ }).sort((a, b) => a.position.x - b.position.x)++ const showHorizontalHelpLineNodesLength = showHorizontalHelpLineNodes.length+ if (showHorizontalHelpLineNodesLength > 0) {+ const first = showHorizontalHelpLineNodes[0]+ const last = showHorizontalHelpLineNodes[showHorizontalHelpLineNodesLength - 1]++ const helpLine = {+ top: first.position.y,+ left: first.position.x,+ width: last.position.x + last.width! - first.position.x,+ }++ if (node.position.x < first.position.x) {+ helpLine.left = node.position.x+ helpLine.width = first.position.x + first.width! - node.position.x+ }++ if (node.position.x > last.position.x)+ helpLine.width = node.position.x + node.width! - first.position.x++ setHelpLineHorizontal(helpLine)+ }+ else {+ setHelpLineHorizontal()+ }++ const showVerticalHelpLineNodes = nodes.filter((n) => {+ if (n.id === node.id)+ return false+ if (n.data.isInIteration)+ return false++ const nX = Math.ceil(n.position.x)+ const nodeX = Math.ceil(node.position.x)++ if (nX - nodeX < 5 && nX - nodeX > -5)+ return true++ return false+ }).sort((a, b) => a.position.x - b.position.x)+ const showVerticalHelpLineNodesLength = showVerticalHelpLineNodes.length++ if (showVerticalHelpLineNodesLength > 0) {+ const first = showVerticalHelpLineNodes[0]+ const last = showVerticalHelpLineNodes[showVerticalHelpLineNodesLength - 1]++ const helpLine = {+ top: first.position.y,+ left: first.position.x,+ height: last.position.y + last.height! - first.position.y,+ }++ if (node.position.y < first.position.y) {+ helpLine.top = node.position.y+ helpLine.height = first.position.y + first.height! - node.position.y+ }++ if (node.position.y > last.position.y)+ helpLine.height = node.position.y + node.height! - first.position.y++ setHelpLineVertical(helpLine)+ }+ else {+ setHelpLineVertical()+ }++ return {+ showHorizontalHelpLineNodes,+ showVerticalHelpLineNodes,+ }+ }, [store, workflowStore])++ return {+ handleSetHelpline,+ }+}diff --git a/web/app/components/workflow/hooks/use-node-data-update.ts b/web/app/components/workflow/hooks/use-node-data-update.tsindex 73574a0485c..4cb4d6b26bc 100644--- a/web/app/components/workflow/hooks/use-node-data-update.ts+++ b/web/app/components/workflow/hooks/use-node-data-update.ts@@ -22,7 +22,7 @@ export const useNodeDataUpdate = () => {const newNodes = produce(getNodes(), (draft) => {const currentNode = draft.find(node => node.id === id)!- currentNode.data = { ...currentNode.data, ...data }+ currentNode.data = { ...currentNode?.data, ...data }})setNodes(newNodes)}, [store])diff --git a/web/app/components/workflow/hooks/use-nodes-data.ts b/web/app/components/workflow/hooks/use-nodes-data.tsindex fc4cb30b5d8..3017f5005ab 100644--- a/web/app/components/workflow/hooks/use-nodes-data.ts+++ b/web/app/components/workflow/hooks/use-nodes-data.ts@@ -1,7 +1,7 @@import { useMemo } from 'react'import { useTranslation } from 'react-i18next'import produce from 'immer'-import type { BlockEnum } from '../types'+import { BlockEnum } from '../types'import {NODES_EXTRA_DATA,NODES_INITIAL_DATA,@@ -30,3 +30,33 @@ export const useNodesExtraData = () => {})}), [t, isChatMode])}++export const useAvailableBlocks = (nodeType?: BlockEnum, isInIteration?: boolean) => {+ const nodesExtraData = useNodesExtraData()+ const availablePrevBlocks = useMemo(() => {+ if (!nodeType)+ return []+ return nodesExtraData[nodeType].availablePrevNodes || []+ }, [nodeType, nodesExtraData])++ const availableNextBlocks = useMemo(() => {+ if (!nodeType)+ return []+ return nodesExtraData[nodeType].availableNextNodes || []+ }, [nodeType, nodesExtraData])++ return useMemo(() => {+ return {+ availablePrevBlocks: availablePrevBlocks.filter((nType) => {+ if (isInIteration && (nType === BlockEnum.Iteration || nType === BlockEnum.End))+ return false+ return true+ }),+ availableNextBlocks: availableNextBlocks.filter((nType) => {+ if (isInIteration && (nType === BlockEnum.Iteration || nType === BlockEnum.End))+ return false+ return true+ }),+ }+ }, [isInIteration, availablePrevBlocks, availableNextBlocks])+}diff --git a/web/app/components/workflow/hooks/use-nodes-interactions.ts b/web/app/components/workflow/hooks/use-nodes-interactions.tsindex a1951e46c2e..edcfd468498 100644--- a/web/app/components/workflow/hooks/use-nodes-interactions.ts+++ b/web/app/components/workflow/hooks/use-nodes-interactions.ts@@ -3,11 +3,12 @@ import { useCallback, useRef } from 'react'import { useTranslation } from 'react-i18next'import produce from 'immer'import type {- HandleType,NodeDragHandler,NodeMouseHandler,OnConnect,+ OnConnectEnd,OnConnectStart,+ ResizeParamsWithDirection,} from 'reactflow'import {getConnectedEdges,@@ -24,8 +25,11 @@ import type {import { BlockEnum } from '../types'import { useWorkflowStore } from '../store'import {+ ITERATION_CHILDREN_Z_INDEX,+ ITERATION_PADDING,NODES_INITIAL_DATA,NODE_WIDTH_X_OFFSET,+ X_OFFSET,Y_OFFSET,} from '../constants'import {@@ -33,8 +37,11 @@ import {getNodesConnectedSourceOrTargetHandleIdsMap,getTopLeftNodePosition,} from '../utils'-import { useNodesExtraData } from './use-nodes-data'+import type { IterationNodeType } from '../nodes/iteration/types'+import type { VariableAssignerNodeType } from '../nodes/variable-assigner/types'+import { useNodeIterationInteractions } from '../nodes/iteration/use-interactions'import { useNodesSyncDraft } from './use-nodes-sync-draft'+import { useHelpline } from './use-helpline'import {useNodesReadOnly,useWorkflow,@@ -45,15 +52,17 @@ export const useNodesInteractions = () => {const store = useStoreApi()const workflowStore = useWorkflowStore()const reactflow = useReactFlow()- const nodesExtraData = useNodesExtraData()const { handleSyncWorkflowDraft } = useNodesSyncDraft()const {getAfterNodesInSameBranch,- getTreeLeafNodes,} = useWorkflow()const { getNodesReadOnly } = useNodesReadOnly()+ const { handleSetHelpline } = useHelpline()+ const {+ handleNodeIterationChildDrag,+ handleNodeIterationChildrenCopy,+ } = useNodeIterationInteractions()const dragNodeStartPosition = useRef({ x: 0, y: 0 } as { x: number; y: number })- const connectingNodeRef = useRef<{ nodeId: string; handleType: HandleType } | null>(null)const handleNodeDragStart = useCallback<NodeDragHandler>((_, node) => {workflowStore.setState({ nodeAnimation: false })@@ -61,6 +70,9 @@ export const useNodesInteractions = () => {if (getNodesReadOnly())return+ if (node.data.isIterationStart)+ return+dragNodeStartPosition.current = { x: node.position.x, y: node.position.y }}, [workflowStore, getNodesReadOnly])@@ -68,104 +80,46 @@ export const useNodesInteractions = () => {if (getNodesReadOnly())return+ if (node.data.isIterationStart)+ return+const {getNodes,setNodes,} = store.getState()- const {- setHelpLineHorizontal,- setHelpLineVertical,- } = workflowStore.getState()e.stopPropagation()const nodes = getNodes()- const showHorizontalHelpLineNodes = nodes.filter((n) => {- if (n.id === node.id)- return false-- const nY = Math.ceil(n.position.y)- const nodeY = Math.ceil(node.position.y)-- if (nY - nodeY < 5 && nY - nodeY > -5)- return true+ const { restrictPosition } = handleNodeIterationChildDrag(node)- return false- }).sort((a, b) => a.position.x - b.position.x)+ const {+ showHorizontalHelpLineNodes,+ showVerticalHelpLineNodes,+ } = handleSetHelpline(node)const showHorizontalHelpLineNodesLength = showHorizontalHelpLineNodes.length- if (showHorizontalHelpLineNodesLength > 0) {- const first = showHorizontalHelpLineNodes[0]- const last = showHorizontalHelpLineNodes[showHorizontalHelpLineNodesLength - 1]-- const helpLine = {- top: first.position.y,- left: first.position.x,- width: last.position.x + last.width! - first.position.x,- }-- if (node.position.x < first.position.x) {- helpLine.left = node.position.x- helpLine.width = first.position.x + first.width! - node.position.x- }-- if (node.position.x > last.position.x)- helpLine.width = node.position.x + node.width! - first.position.x-- setHelpLineHorizontal(helpLine)- }- else {- setHelpLineHorizontal()- }-- const showVerticalHelpLineNodes = nodes.filter((n) => {- if (n.id === node.id)- return false-- const nX = Math.ceil(n.position.x)- const nodeX = Math.ceil(node.position.x)-- if (nX - nodeX < 5 && nX - nodeX > -5)- return true-- return false- }).sort((a, b) => a.position.x - b.position.x)const showVerticalHelpLineNodesLength = showVerticalHelpLineNodes.length- if (showVerticalHelpLineNodesLength > 0) {- const first = showVerticalHelpLineNodes[0]- const last = showVerticalHelpLineNodes[showVerticalHelpLineNodesLength - 1]-- const helpLine = {- top: first.position.y,- left: first.position.x,- height: last.position.y + last.height! - first.position.y,- }-- if (node.position.y < first.position.y) {- helpLine.top = node.position.y- helpLine.height = first.position.y + first.height! - node.position.y- }-- if (node.position.y > last.position.y)- helpLine.height = node.position.y + node.height! - first.position.y-- setHelpLineVertical(helpLine)- }- else {- setHelpLineVertical()- }-const newNodes = produce(nodes, (draft) => {const currentNode = draft.find(n => n.id === node.id)!- currentNode.position = {- x: showVerticalHelpLineNodesLength > 0 ? showVerticalHelpLineNodes[0].position.x : node.position.x,- y: showHorizontalHelpLineNodesLength > 0 ? showHorizontalHelpLineNodes[0].position.y : node.position.y,- }+ if (showVerticalHelpLineNodesLength > 0)+ currentNode.position.x = showVerticalHelpLineNodes[0].position.x+ else if (restrictPosition.x !== undefined)+ currentNode.position.x = restrictPosition.x+ else+ currentNode.position.x = node.position.x++ if (showHorizontalHelpLineNodesLength > 0)+ currentNode.position.y = showHorizontalHelpLineNodes[0].position.y+ else if (restrictPosition.y !== undefined)+ currentNode.position.y = restrictPosition.y+ else+ currentNode.position.y = node.position.y})setNodes(newNodes)- }, [store, workflowStore, getNodesReadOnly])+ }, [store, getNodesReadOnly, handleSetHelpline, handleNodeIterationChildDrag])const handleNodeDragStop = useCallback<NodeDragHandler>((_, node) => {const {@@ -195,20 +149,35 @@ export const useNodesInteractions = () => {setEdges,} = store.getState()const nodes = getNodes()+ const {+ connectingNodePayload,+ setEnteringNodePayload,+ } = workflowStore.getState()- if (connectingNodeRef.current && connectingNodeRef.current.nodeId !== node.id) {- const connectingNode: Node = nodes.find(n => n.id === connectingNodeRef.current!.nodeId)!- const handleType = connectingNodeRef.current.handleType- const currentNodeIndex = nodes.findIndex(n => n.id === node.id)- const availablePrevNodes = nodesExtraData[connectingNode.data.type].availablePrevNodes- const availableNextNodes = nodesExtraData[connectingNode.data.type].availableNextNodes- const availableNodes = handleType === 'source' ? availableNextNodes : [...availablePrevNodes, BlockEnum.Start]+ if (connectingNodePayload) {+ if (connectingNodePayload.nodeId === node.id)+ return+ const connectingNode: Node = nodes.find(n => n.id === connectingNodePayload.nodeId)!+ const sameLevel = connectingNode.parentId === node.parentId- const newNodes = produce(nodes, (draft) => {- if (!availableNodes.includes(draft[currentNodeIndex].data.type))- draft[currentNodeIndex].data._isInvalidConnection = true- })- setNodes(newNodes)+ if (sameLevel) {+ setEnteringNodePayload({+ nodeId: node.id,+ })+ const fromType = connectingNodePayload.handleType++ const newNodes = produce(nodes, (draft) => {+ draft.forEach((n) => {+ if (n.id === node.id && fromType === 'source' && (node.data.type === BlockEnum.VariableAssigner || node.data.type === BlockEnum.VariableAggregator)) {+ if (!node.data.advanced_settings?.group_enabled)+ n.data._isEntering = true+ }+ if (n.id === node.id && fromType === 'target' && (connectingNode.data.type === BlockEnum.VariableAssigner || connectingNode.data.type === BlockEnum.VariableAggregator) && node.data.type !== BlockEnum.IfElse && node.data.type !== BlockEnum.QuestionClassifier)+ n.data._isEntering = true+ })+ })+ setNodes(newNodes)+ }}const newEdges = produce(edges, (draft) => {const connectedEdges = getConnectedEdges([node], edges)@@ -220,12 +189,16 @@ export const useNodesInteractions = () => {})})setEdges(newEdges)- }, [store, nodesExtraData, getNodesReadOnly])+ }, [store, workflowStore, getNodesReadOnly])const handleNodeLeave = useCallback<NodeMouseHandler>(() => {if (getNodesReadOnly())return+ const {+ setEnteringNodePayload,+ } = workflowStore.getState()+ setEnteringNodePayload(undefined)const {getNodes,setNodes,@@ -234,7 +207,7 @@ export const useNodesInteractions = () => {} = store.getState()const newNodes = produce(getNodes(), (draft) => {draft.forEach((node) => {- node.data._isInvalidConnection = false+ node.data._isEntering = false})})setNodes(newNodes)@@ -244,7 +217,7 @@ export const useNodesInteractions = () => {})})setEdges(newEdges)- }, [store, getNodesReadOnly])+ }, [store, workflowStore, getNodesReadOnly])const handleNodeSelect = useCallback((nodeId: string, cancelSelection?: boolean) => {const {@@ -315,16 +288,18 @@ export const useNodesInteractions = () => {} = store.getState()const nodes = getNodes()const targetNode = nodes.find(node => node.id === target!)- if (targetNode && targetNode?.data.type === BlockEnum.VariableAssigner) {- const treeNodes = getTreeLeafNodes(target!)+ const sourceNode = nodes.find(node => node.id === source!)++ if (targetNode?.parentId !== sourceNode?.parentId)+ return++ if (targetNode?.data.isIterationStart)+ return- if (!treeNodes.find(treeNode => treeNode.id === source))- return- }const needDeleteEdges = edges.filter((edge) => {if ((edge.source === source && edge.sourceHandle === sourceHandle)- || (edge.target === target && edge.targetHandle === targetHandle)+ || (edge.target === target && edge.targetHandle === targetHandle && targetNode?.data.type !== BlockEnum.VariableAssigner && targetNode?.data.type !== BlockEnum.VariableAggregator))return true@@ -332,7 +307,7 @@ export const useNodesInteractions = () => {})const needDeleteEdgesIds = needDeleteEdges.map(edge => edge.id)const newEdge = {- id: `${source}-${target}`,+ id: `${source}-${sourceHandle}-${target}-${targetHandle}`,type: 'custom',source: source!,target: target!,@@ -341,7 +316,10 @@ export const useNodesInteractions = () => {data: {sourceType: nodes.find(node => node.id === source)!.data.type,targetType: nodes.find(node => node.id === target)!.data.type,+ isInIteration: !!targetNode?.parentId,+ iteration_id: targetNode?.parentId,},+ zIndex: targetNode?.parentId ? ITERATION_CHILDREN_Z_INDEX : 0,}const nodesConnectedSourceOrTargetHandleIdsMap = getNodesConnectedSourceOrTargetHandleIdsMap([@@ -370,20 +348,126 @@ export const useNodesInteractions = () => {})setEdges(newEdges)handleSyncWorkflowDraft()- }, [store, handleSyncWorkflowDraft, getNodesReadOnly, getTreeLeafNodes])+ }, [store, handleSyncWorkflowDraft, getNodesReadOnly])++ const handleNodeConnectStart = useCallback<OnConnectStart>((_, { nodeId, handleType, handleId }) => {+ if (getNodesReadOnly())+ return- const handleNodeConnectStart = useCallback<OnConnectStart>((_, { nodeId, handleType }) => {if (nodeId && handleType) {- connectingNodeRef.current = {- nodeId,- handleType,+ const { setConnectingNodePayload } = workflowStore.getState()+ const { getNodes } = store.getState()+ const node = getNodes().find(n => n.id === nodeId)!++ if (!node.data.isIterationStart) {+ setConnectingNodePayload({+ nodeId,+ nodeType: node.data.type,+ handleType,+ handleId,+ })}}- }, [])+ }, [store, workflowStore, getNodesReadOnly])- const handleNodeConnectEnd = useCallback(() => {- connectingNodeRef.current = null- }, [])+ const handleNodeConnectEnd = useCallback<OnConnectEnd>((e: any) => {+ if (getNodesReadOnly())+ return++ const {+ connectingNodePayload,+ setConnectingNodePayload,+ enteringNodePayload,+ setEnteringNodePayload,+ } = workflowStore.getState()+ if (connectingNodePayload && enteringNodePayload) {+ const {+ setShowAssignVariablePopup,+ hoveringAssignVariableGroupId,+ } = workflowStore.getState()+ const { screenToFlowPosition } = reactflow+ const {+ getNodes,+ setNodes,+ } = store.getState()+ const nodes = getNodes()+ const fromHandleType = connectingNodePayload.handleType+ const fromHandleId = connectingNodePayload.handleId+ const fromNode = nodes.find(n => n.id === connectingNodePayload.nodeId)!+ const fromNodeParent = nodes.find(n => n.id === fromNode.parentId)+ const toNode = nodes.find(n => n.id === enteringNodePayload.nodeId)!+ const toParentNode = nodes.find(n => n.id === toNode.parentId)++ if (fromNode.parentId !== toNode.parentId)+ return++ const { x, y } = screenToFlowPosition({ x: e.x, y: e.y })++ if (fromHandleType === 'source' && (toNode.data.type === BlockEnum.VariableAssigner || toNode.data.type === BlockEnum.VariableAggregator)) {+ const groupEnabled = toNode.data.advanced_settings?.group_enabled++ if (+ (groupEnabled && hoveringAssignVariableGroupId)+ || !groupEnabled+ ) {+ const newNodes = produce(nodes, (draft) => {+ draft.forEach((node) => {+ if (node.id === toNode.id) {+ node.data._showAddVariablePopup = true+ node.data._holdAddVariablePopup = true+ }+ })+ })+ setNodes(newNodes)+ setShowAssignVariablePopup({+ nodeId: fromNode.id,+ nodeData: fromNode.data,+ variableAssignerNodeId: toNode.id,+ variableAssignerNodeData: toNode.data,+ variableAssignerNodeHandleId: hoveringAssignVariableGroupId || 'target',+ parentNode: toParentNode,+ x: x - toNode.positionAbsolute!.x,+ y: y - toNode.positionAbsolute!.y,+ })+ handleNodeConnect({+ source: fromNode.id,+ sourceHandle: fromHandleId,+ target: toNode.id,+ targetHandle: hoveringAssignVariableGroupId || 'target',+ })+ }+ }+ if (fromHandleType === 'target' && (fromNode.data.type === BlockEnum.VariableAssigner || fromNode.data.type === BlockEnum.VariableAggregator) && toNode.data.type !== BlockEnum.IfElse && toNode.data.type !== BlockEnum.QuestionClassifier) {+ const newNodes = produce(nodes, (draft) => {+ draft.forEach((node) => {+ if (node.id === toNode.id) {+ node.data._showAddVariablePopup = true+ node.data._holdAddVariablePopup = true+ }+ })+ })+ setNodes(newNodes)+ setShowAssignVariablePopup({+ nodeId: toNode.id,+ nodeData: toNode.data,+ variableAssignerNodeId: fromNode.id,+ variableAssignerNodeData: fromNode.data,+ variableAssignerNodeHandleId: fromHandleId || 'target',+ parentNode: fromNodeParent,+ x: x - toNode.positionAbsolute!.x,+ y: y - toNode.positionAbsolute!.y,+ })+ handleNodeConnect({+ source: toNode.id,+ sourceHandle: 'source',+ target: fromNode.id,+ targetHandle: fromHandleId,+ })+ }+ }+ setConnectingNodePayload(undefined)+ setEnteringNodePayload(undefined)+ }, [store, handleNodeConnect, getNodesReadOnly, workflowStore, reactflow])const handleNodeDelete = useCallback((nodeId: string) => {if (getNodesReadOnly())@@ -398,8 +482,45 @@ export const useNodesInteractions = () => {const nodes = getNodes()const currentNodeIndex = nodes.findIndex(node => node.id === nodeId)- if (nodes[currentNodeIndex].data.type === BlockEnum.Start)+ const currentNode = nodes[currentNodeIndex]++ if (!currentNode)+ return++ if (currentNode.data.type === BlockEnum.Start)return++ if (currentNode.data.type === BlockEnum.Iteration) {+ const iterationChildren = nodes.filter(node => node.parentId === currentNode.id)++ if (iterationChildren.length) {+ if (currentNode.data._isBundled) {+ iterationChildren.forEach((child) => {+ handleNodeDelete(child.id)+ })+ return handleNodeDelete(nodeId)+ }+ else {+ const { setShowConfirm, showConfirm } = workflowStore.getState()++ if (!showConfirm) {+ setShowConfirm({+ title: t('workflow.nodes.iteration.deleteTitle'),+ desc: t('workflow.nodes.iteration.deleteDesc') || '',+ onConfirm: () => {+ iterationChildren.forEach((child) => {+ handleNodeDelete(child.id)+ })+ handleNodeDelete(nodeId)+ handleSyncWorkflowDraft()+ setShowConfirm(undefined)+ },+ })+ return+ }+ }+ }+ }const connectedEdges = getConnectedEdges([{ id: nodeId } as Node], edges)const nodesConnectedSourceOrTargetHandleIdsMap = getNodesConnectedSourceOrTargetHandleIdsMap(connectedEdges.map(edge => ({ type: 'remove', edge })), nodes)const newNodes = produce(nodes, (draft: Node[]) => {@@ -410,6 +531,15 @@ export const useNodesInteractions = () => {...nodesConnectedSourceOrTargetHandleIdsMap[node.id],}}++ if (node.id === currentNode.parentId) {+ node.data._children = node.data._children?.filter(child => child !== nodeId)++ if (currentNode.id === (node as Node<IterationNodeType>).data.start_node_id) {+ (node as Node<IterationNodeType>).data.start_node_id = '';+ (node as Node<IterationNodeType>).data.startNodeType = undefined+ }+ }})draft.splice(currentNodeIndex, 1)})@@ -419,7 +549,7 @@ export const useNodesInteractions = () => {})setEdges(newEdges)handleSyncWorkflowDraft()- }, [store, handleSyncWorkflowDraft, getNodesReadOnly])+ }, [store, handleSyncWorkflowDraft, getNodesReadOnly, workflowStore, t])const handleNodeAdd = useCallback<OnNodeAdd>(({@@ -438,9 +568,6 @@ export const useNodesInteractions = () => {if (getNodesReadOnly())return- if (nodeType === BlockEnum.VariableAssigner)- targetHandle = 'varNotSet'-const {getNodes,setNodes,@@ -455,6 +582,8 @@ export const useNodesInteractions = () => {title: nodesWithSameType.length > 0 ? `${t(`workflow.blocks.${nodeType}`)} ${nodesWithSameType.length + 1}` : t(`workflow.blocks.${nodeType}`),...(toolDefaultValue || {}),selected: true,+ _showAddVariablePopup: (nodeType === BlockEnum.VariableAssigner || nodeType === BlockEnum.VariableAggregator) && !!prevNodeId,+ _holdAddVariablePopup: false,},position: {x: 0,@@ -470,12 +599,19 @@ export const useNodesInteractions = () => {newNode.data._connectedTargetHandleIds = [targetHandle]newNode.data._connectedSourceHandleIds = []newNode.position = {- x: lastOutgoer ? lastOutgoer.position.x : prevNode.position.x + NODE_WIDTH_X_OFFSET,+ x: lastOutgoer ? lastOutgoer.position.x : prevNode.position.x + prevNode.width! + X_OFFSET,y: lastOutgoer ? lastOutgoer.position.y + lastOutgoer.height! + Y_OFFSET : prevNode.position.y,}+ newNode.parentId = prevNode.parentId+ newNode.extent = prevNode.extent+ if (prevNode.parentId) {+ newNode.data.isInIteration = true+ newNode.data.iteration_id = prevNode.parentId+ newNode.zIndex = ITERATION_CHILDREN_Z_INDEX+ }- const newEdge = {- id: `${prevNodeId}-${newNode.id}`,+ const newEdge: Edge = {+ id: `${prevNodeId}-${prevNodeSourceHandle}-${newNode.id}-${targetHandle}`,type: 'custom',source: prevNodeId,sourceHandle: prevNodeSourceHandle,@@ -484,8 +620,11 @@ export const useNodesInteractions = () => {data: {sourceType: prevNode.data.type,targetType: newNode.data.type,+ isInIteration: !!prevNode.parentId,+ iteration_id: prevNode.parentId,_connectedNodeIsSelected: true,},+ zIndex: prevNode.parentId ? ITERATION_CHILDREN_Z_INDEX : 0,}const nodesConnectedSourceOrTargetHandleIdsMap = getNodesConnectedSourceOrTargetHandleIdsMap([@@ -503,10 +642,27 @@ export const useNodesInteractions = () => {...nodesConnectedSourceOrTargetHandleIdsMap[node.id],}}++ if (node.data.type === BlockEnum.Iteration && prevNode.parentId === node.id)+ node.data._children?.push(newNode.id)})draft.push(newNode)})setNodes(newNodes)+ if (newNode.data.type === BlockEnum.VariableAssigner || newNode.data.type === BlockEnum.VariableAggregator) {+ const { setShowAssignVariablePopup } = workflowStore.getState()++ setShowAssignVariablePopup({+ nodeId: prevNode.id,+ nodeData: prevNode.data,+ variableAssignerNodeId: newNode.id,+ variableAssignerNodeData: (newNode.data as VariableAssignerNodeType),+ variableAssignerNodeHandleId: targetHandle,+ parentNode: nodes.find(node => node.id === newNode.parentId),+ x: -25,+ y: 44,+ })+ }const newEdges = produce(edges, (draft) => {draft.forEach((item) => {item.data = {@@ -528,12 +684,21 @@ export const useNodesInteractions = () => {x: nextNode.position.x,y: nextNode.position.y,}+ newNode.parentId = nextNode.parentId+ newNode.extent = nextNode.extent+ if (nextNode.parentId) {+ newNode.data.isInIteration = true+ newNode.data.iteration_id = nextNode.parentId+ newNode.zIndex = ITERATION_CHILDREN_Z_INDEX+ }+ if (nextNode.data.isIterationStart)+ newNode.data.isIterationStart = truelet newEdgeif ((nodeType !== BlockEnum.IfElse) && (nodeType !== BlockEnum.QuestionClassifier)) {newEdge = {- id: `${newNode.id}-${nextNodeId}`,+ id: `${newNode.id}-${sourceHandle}-${nextNodeId}-${nextNodeTargetHandle}`,type: 'custom',source: newNode.id,sourceHandle,@@ -542,8 +707,11 @@ export const useNodesInteractions = () => {data: {sourceType: newNode.data.type,targetType: nextNode.data.type,+ isInIteration: !!nextNode.parentId,+ iteration_id: nextNode.parentId,_connectedNodeIsSelected: true,},+ zIndex: nextNode.parentId ? ITERATION_CHILDREN_Z_INDEX : 0,}}@@ -572,6 +740,17 @@ export const useNodesInteractions = () => {...nodesConnectedSourceOrTargetHandleIdsMap[node.id],}}++ if (node.data.type === BlockEnum.Iteration && nextNode.parentId === node.id)+ node.data._children?.push(newNode.id)++ if (node.data.type === BlockEnum.Iteration && node.data.start_node_id === nextNodeId) {+ node.data.start_node_id = newNode.id+ node.data.startNodeType = newNode.data.type+ }++ if (node.id === nextNodeId && node.data.isIterationStart)+ node.data.isIterationStart = false})draft.push(newNode)})@@ -599,10 +778,17 @@ export const useNodesInteractions = () => {x: nextNode.position.x,y: nextNode.position.y,}+ newNode.parentId = prevNode.parentId+ newNode.extent = prevNode.extent+ if (prevNode.parentId) {+ newNode.data.isInIteration = true+ newNode.data.iteration_id = prevNode.parentId+ newNode.zIndex = ITERATION_CHILDREN_Z_INDEX+ }const currentEdgeIndex = edges.findIndex(edge => edge.source === prevNodeId && edge.target === nextNodeId)const newPrevEdge = {- id: `${prevNodeId}-${newNode.id}`,+ id: `${prevNodeId}-${prevNodeSourceHandle}-${newNode.id}-${targetHandle}`,type: 'custom',source: prevNodeId,sourceHandle: prevNodeSourceHandle,@@ -611,13 +797,16 @@ export const useNodesInteractions = () => {data: {sourceType: prevNode.data.type,targetType: newNode.data.type,+ isInIteration: !!prevNode.parentId,+ iteration_id: prevNode.parentId,_connectedNodeIsSelected: true,},+ zIndex: prevNode.parentId ? ITERATION_CHILDREN_Z_INDEX : 0,}let newNextEdge: Edge | null = nullif (nodeType !== BlockEnum.IfElse && nodeType !== BlockEnum.QuestionClassifier) {newNextEdge = {- id: `${newNode.id}-${nextNodeId}`,+ id: `${newNode.id}-${sourceHandle}-${nextNodeId}-${nextNodeTargetHandle}`,type: 'custom',source: newNode.id,sourceHandle,@@ -626,8 +815,11 @@ export const useNodesInteractions = () => {data: {sourceType: newNode.data.type,targetType: nextNode.data.type,+ isInIteration: !!nextNode.parentId,+ iteration_id: nextNode.parentId,_connectedNodeIsSelected: true,},+ zIndex: nextNode.parentId ? ITERATION_CHILDREN_Z_INDEX : 0,}}const nodesConnectedSourceOrTargetHandleIdsMap = getNodesConnectedSourceOrTargetHandleIdsMap(@@ -653,10 +845,27 @@ export const useNodesInteractions = () => {}if (afterNodesInSameBranchIds.includes(node.id))node.position.x += NODE_WIDTH_X_OFFSET++ if (node.data.type === BlockEnum.Iteration && prevNode.parentId === node.id)+ node.data._children?.push(newNode.id)})draft.push(newNode)})setNodes(newNodes)+ if (newNode.data.type === BlockEnum.VariableAssigner || newNode.data.type === BlockEnum.VariableAggregator) {+ const { setShowAssignVariablePopup } = workflowStore.getState()++ setShowAssignVariablePopup({+ nodeId: prevNode.id,+ nodeData: prevNode.data,+ variableAssignerNodeId: newNode.id,+ variableAssignerNodeData: newNode.data as VariableAssignerNodeType,+ variableAssignerNodeHandleId: targetHandle,+ parentNode: nodes.find(node => node.id === newNode.parentId),+ x: -25,+ y: 44,+ })+ }const newEdges = produce(edges, (draft) => {draft.splice(currentEdgeIndex, 1)draft.forEach((item) => {@@ -673,7 +882,7 @@ export const useNodesInteractions = () => {setEdges(newEdges)}handleSyncWorkflowDraft()- }, [store, handleSyncWorkflowDraft, getAfterNodesInSameBranch, getNodesReadOnly, t])+ }, [store, workflowStore, handleSyncWorkflowDraft, getAfterNodesInSameBranch, getNodesReadOnly, t])const handleNodeChange = useCallback((currentNodeId: string,@@ -702,11 +911,17 @@ export const useNodesInteractions = () => {_connectedSourceHandleIds: [],_connectedTargetHandleIds: [],selected: currentNode.data.selected,+ isInIteration: currentNode.data.isInIteration,+ iteration_id: currentNode.data.iteration_id,+ isIterationStart: currentNode.data.isIterationStart,},position: {x: currentNode.position.x,y: currentNode.position.y,},+ parentId: currentNode.parentId,+ extent: currentNode.extent,+ zIndex: currentNode.zIndex,})const nodesConnectedSourceOrTargetHandleIdsMap = getNodesConnectedSourceOrTargetHandleIdsMap([@@ -724,6 +939,14 @@ export const useNodesInteractions = () => {...nodesConnectedSourceOrTargetHandleIdsMap[node.id],}}+ if (node.id === currentNode.parentId && currentNode.data.isIterationStart) {+ node.data._children = [+ newCurrentNode.id,+ ...(node.data._children || []),+ ].filter(child => child !== currentNodeId)+ node.data.start_node_id = newCurrentNode.id+ node.data.startNodeType = newCurrentNode.data.type+ }})const index = draft.findIndex(node => node.id === currentNodeId)@@ -801,7 +1024,7 @@ export const useNodesInteractions = () => {} = store.getState()const nodes = getNodes()- const bundledNodes = nodes.filter(node => node.data._isBundled && node.data.type !== BlockEnum.Start)+ const bundledNodes = nodes.filter(node => node.data._isBundled && node.data.type !== BlockEnum.Start && !node.data.isInIteration)if (bundledNodes.length) {setClipboardElements(bundledNodes)@@ -860,51 +1083,43 @@ export const useNodesInteractions = () => {x: nodeToPaste.position.x + offsetX,y: nodeToPaste.position.y + offsetY,},+ extent: nodeToPaste.extent,+ zIndex: nodeToPaste.zIndex,})newNode.id = newNode.id + index++ let newChildren: Node[] = []+ if (nodeToPaste.data.type === BlockEnum.Iteration) {+ newNode.data._children = [];+ (newNode.data as IterationNodeType).start_node_id = ''++ newChildren = handleNodeIterationChildrenCopy(nodeToPaste.id, newNode.id)++ newChildren.forEach((child) => {+ newNode.data._children?.push(child.id)+ if (child.data.isIterationStart)+ (newNode.data as IterationNodeType).start_node_id = child.id+ })+ }+nodesToPaste.push(newNode)++ if (newChildren.length)+ nodesToPaste.push(...newChildren)})setNodes([...nodes, ...nodesToPaste])handleSyncWorkflowDraft()}- }, [t, getNodesReadOnly, store, workflowStore, handleSyncWorkflowDraft, reactflow])+ }, [t, getNodesReadOnly, store, workflowStore, handleSyncWorkflowDraft, reactflow, handleNodeIterationChildrenCopy])const handleNodesDuplicate = useCallback(() => {if (getNodesReadOnly())return- const {- getNodes,- setNodes,- } = store.getState()- const nodes = getNodes()-- const selectedNode = nodes.find(node => node.data.selected && node.data.type !== BlockEnum.Start)-- if (selectedNode) {- const nodeType = selectedNode.data.type- const nodesWithSameType = nodes.filter(node => node.data.type === nodeType)-- const newNode = generateNewNode({- data: {- ...NODES_INITIAL_DATA[nodeType as BlockEnum],- ...selectedNode.data,- selected: false,- _isBundled: false,- _connectedSourceHandleIds: [],- _connectedTargetHandleIds: [],- title: nodesWithSameType.length > 0 ? `${t(`workflow.blocks.${nodeType}`)} ${nodesWithSameType.length + 1}` : t(`workflow.blocks.${nodeType}`),- },- position: {- x: selectedNode.position.x + selectedNode.width! + 10,- y: selectedNode.position.y,- },- })-- setNodes([...nodes, newNode])- }- }, [store, t, getNodesReadOnly])+ handleNodesCopy()+ handleNodesPaste()+ }, [getNodesReadOnly, handleNodesCopy, handleNodesPaste])const handleNodesDelete = useCallback(() => {if (getNodesReadOnly())@@ -928,6 +1143,7 @@ export const useNodesInteractions = () => {if (bundledNodes.length) {bundledNodes.forEach(node => handleNodeDelete(node.id))+return}@@ -941,6 +1157,61 @@ export const useNodesInteractions = () => {handleNodeDelete(selectedNode.id)}, [store, workflowStore, getNodesReadOnly, handleNodeDelete])+ const handleNodeResize = useCallback((nodeId: string, params: ResizeParamsWithDirection) => {+ if (getNodesReadOnly())+ return++ const {+ getNodes,+ setNodes,+ } = store.getState()+ const { x, y, width, height } = params++ const nodes = getNodes()+ const currentNode = nodes.find(n => n.id === nodeId)!+ const childrenNodes = nodes.filter(n => currentNode.data._children?.includes(n.id))+ let rightNode: Node+ let bottomNode: Node++ childrenNodes.forEach((n) => {+ if (rightNode) {+ if (n.position.x + n.width! > rightNode.position.x + rightNode.width!)+ rightNode = n+ }+ else {+ rightNode = n+ }+ if (bottomNode) {+ if (n.position.y + n.height! > bottomNode.position.y + bottomNode.height!)+ bottomNode = n+ }+ else {+ bottomNode = n+ }+ })++ if (rightNode! && bottomNode!) {+ if (width < rightNode!.position.x + rightNode.width! + ITERATION_PADDING.right)+ return+ if (height < bottomNode.position.y + bottomNode.height! + ITERATION_PADDING.bottom)+ return+ }+ const newNodes = produce(nodes, (draft) => {+ draft.forEach((n) => {+ if (n.id === nodeId) {+ n.data.width = width+ n.data.height = height+ n.width = width+ n.height = height+ n.position.x = x+ n.position.y = y+ }+ })+ })+ setNodes(newNodes)+ handleSyncWorkflowDraft()+ }, [store, getNodesReadOnly, handleSyncWorkflowDraft])+return {handleNodeDragStart,handleNodeDrag,@@ -962,5 +1233,6 @@ export const useNodesInteractions = () => {handleNodesPaste,handleNodesDuplicate,handleNodesDelete,+ handleNodeResize,}}diff --git a/web/app/components/workflow/hooks/use-nodes-layout.ts b/web/app/components/workflow/hooks/use-nodes-layout.tsnew file mode 100644index 00000000000..594ac8b0294--- /dev/null+++ b/web/app/components/workflow/hooks/use-nodes-layout.ts@@ -0,0 +1,96 @@+import { useCallback } from 'react'+import ELK from 'elkjs/lib/elk.bundled.js'+import {+ useReactFlow,+ useStoreApi,+} from 'reactflow'+import { cloneDeep } from 'lodash-es'+import type {+ Edge,+ Node,+} from '../types'+import { useWorkflowStore } from '../store'+import { AUTO_LAYOUT_OFFSET } from '../constants'+import { useNodesSyncDraft } from './use-nodes-sync-draft'++const layoutOptions = {+ 'elk.algorithm': 'layered',+ 'elk.direction': 'RIGHT',+ 'elk.layered.spacing.nodeNodeBetweenLayers': '60',+ 'elk.spacing.nodeNode': '40',+ 'elk.layered.nodePlacement.strategy': 'SIMPLE',+}++const elk = new ELK()++export const getLayoutedNodes = async (nodes: Node[], edges: Edge[]) => {+ const graph = {+ id: 'root',+ layoutOptions,+ children: nodes.map((n) => {+ return {+ ...n,+ width: n.width ?? 150,+ height: n.height ?? 50,+ targetPosition: 'left',+ sourcePosition: 'right',+ }+ }),+ edges: cloneDeep(edges),+ }++ const layoutedGraph = await elk.layout(graph as any)+ const layoutedNodes = nodes.map((node) => {+ const layoutedNode = layoutedGraph.children?.find(+ lgNode => lgNode.id === node.id,+ )++ return {+ ...node,+ position: {+ x: (layoutedNode?.x ?? 0) + AUTO_LAYOUT_OFFSET.x,+ y: (layoutedNode?.y ?? 0) + AUTO_LAYOUT_OFFSET.y,+ },+ }+ })++ return {+ layoutedNodes,+ }+}++export const useNodesLayout = () => {+ const store = useStoreApi()+ const reactflow = useReactFlow()+ const workflowStore = useWorkflowStore()+ const { handleSyncWorkflowDraft } = useNodesSyncDraft()++ const handleNodesLayout = useCallback(async () => {+ workflowStore.setState({ nodeAnimation: true })+ const {+ getNodes,+ edges,+ setNodes,+ } = store.getState()+ const { setViewport } = reactflow+ const nodes = getNodes()+ const {+ layoutedNodes,+ } = await getLayoutedNodes(nodes, edges)++ setNodes(layoutedNodes)+ const zoom = 0.7+ setViewport({+ x: 0,+ y: 0,+ zoom,+ })+ setTimeout(() => {+ handleSyncWorkflowDraft()+ })+ }, [store, reactflow, handleSyncWorkflowDraft, workflowStore])++ return {+ handleNodesLayout,+ }+}diff --git a/web/app/components/workflow/hooks/use-workflow-run.ts b/web/app/components/workflow/hooks/use-workflow-run.tsindex 17f4371414d..bb2758625b5 100644--- a/web/app/components/workflow/hooks/use-workflow-run.ts+++ b/web/app/components/workflow/hooks/use-workflow-run.ts@@ -85,6 +85,7 @@ export const useWorkflowRun = () => {const newNodes = produce(getNodes(), (draft) => {draft.forEach((node) => {node.data.selected = false+ node.data._runningStatus = undefined})})setNodes(newNodes)@@ -95,6 +96,9 @@ export const useWorkflowRun = () => {onWorkflowFinished,onNodeStarted,onNodeFinished,+ onIterationStart,+ onIterationNext,+ onIterationFinish,onError,...restCallback} = callback || {}@@ -127,6 +131,9 @@ export const useWorkflowRun = () => {resultText: '',})+ let isInIteration = false+ let iterationLength = 0+ssePost(url,{@@ -176,7 +183,7 @@ export const useWorkflowRun = () => {draft.result = {...draft.result,...data,- }+ } as any}))prevNodeId = ''@@ -201,6 +208,120 @@ export const useWorkflowRun = () => {onError(params)},onNodeStarted: (params) => {+ const { data } = params+ const {+ workflowRunningData,+ setWorkflowRunningData,+ } = workflowStore.getState()+ const {+ getNodes,+ setNodes,+ edges,+ setEdges,+ transform,+ } = store.getState()+ if (isInIteration) {+ setWorkflowRunningData(produce(workflowRunningData!, (draft) => {+ const tracing = draft.tracing!+ const iterations = tracing[tracing.length - 1]+ const currIteration = iterations.details![iterations.details!.length - 1]+ currIteration.push({+ ...data,+ status: NodeRunningStatus.Running,+ } as any)+ }))+ }+ else {+ const nodes = getNodes()+ setWorkflowRunningData(produce(workflowRunningData!, (draft) => {+ draft.tracing!.push({+ ...data,+ status: NodeRunningStatus.Running,+ } as any)+ }))++ const {+ setViewport,+ } = reactflow+ const currentNodeIndex = nodes.findIndex(node => node.id === data.node_id)+ const currentNode = nodes[currentNodeIndex]+ const position = currentNode.position+ const zoom = transform[2]++ if (!currentNode.parentId) {+ setViewport({+ x: (clientWidth - 400 - currentNode.width! * zoom) / 2 - position.x * zoom,+ y: (clientHeight - currentNode.height! * zoom) / 2 - position.y * zoom,+ zoom: transform[2],+ })+ }+ const newNodes = produce(nodes, (draft) => {+ draft[currentNodeIndex].data._runningStatus = NodeRunningStatus.Running+ })+ setNodes(newNodes)+ const newEdges = produce(edges, (draft) => {+ const edge = draft.find(edge => edge.target === data.node_id && edge.source === prevNodeId)++ if (edge)+ edge.data = { ...edge.data, _runned: true } as any+ })+ setEdges(newEdges)+ }+ if (onNodeStarted)+ onNodeStarted(params)+ },+ onNodeFinished: (params) => {+ const { data } = params+ const {+ workflowRunningData,+ setWorkflowRunningData,+ } = workflowStore.getState()+ const {+ getNodes,+ setNodes,+ } = store.getState()+ if (isInIteration) {+ setWorkflowRunningData(produce(workflowRunningData!, (draft) => {+ const tracing = draft.tracing!+ const iterations = tracing[tracing.length - 1]+ const currIteration = iterations.details![iterations.details!.length - 1]+ const nodeInfo = currIteration[currIteration.length - 1]++ currIteration[currIteration.length - 1] = {+ ...nodeInfo,+ ...data,+ status: NodeRunningStatus.Succeeded,+ } as any+ }))+ }+ else {+ const nodes = getNodes()+ setWorkflowRunningData(produce(workflowRunningData!, (draft) => {+ const currentIndex = draft.tracing!.findIndex(trace => trace.node_id === data.node_id)++ if (currentIndex > -1 && draft.tracing) {+ draft.tracing[currentIndex] = {+ ...(draft.tracing[currentIndex].extras+ ? { extras: draft.tracing[currentIndex].extras }+ : {}),+ ...data,+ } as any+ }+ }))++ const newNodes = produce(nodes, (draft) => {+ const currentNode = draft.find(node => node.id === data.node_id)!++ currentNode.data._runningStatus = data.status as any+ })+ setNodes(newNodes)++ prevNodeId = data.node_id+ }+ if (onNodeFinished)+ onNodeFinished(params)+ },+ onIterationStart: (params) => {const { data } = paramsconst {workflowRunningData,@@ -218,8 +339,11 @@ export const useWorkflowRun = () => {draft.tracing!.push({...data,status: NodeRunningStatus.Running,+ details: [],} as any)}))+ isInIteration = true+ iterationLength = data.metadata.iterator_lengthconst {setViewport,@@ -229,13 +353,16 @@ export const useWorkflowRun = () => {const position = currentNode.positionconst zoom = transform[2]- setViewport({- x: (clientWidth - 400 - currentNode.width! * zoom) / 2 - position.x * zoom,- y: (clientHeight - currentNode.height! * zoom) / 2 - position.y * zoom,- zoom: transform[2],- })+ if (!currentNode.parentId) {+ setViewport({+ x: (clientWidth - 400 - currentNode.width! * zoom) / 2 - position.x * zoom,+ y: (clientHeight - currentNode.height! * zoom) / 2 - position.y * zoom,+ zoom: transform[2],+ })+ }const newNodes = produce(nodes, (draft) => {draft[currentNodeIndex].data._runningStatus = NodeRunningStatus.Running+ draft[currentNodeIndex].data._iterationLength = data.metadata.iterator_length})setNodes(newNodes)const newEdges = produce(edges, (draft) => {@@ -246,11 +373,43 @@ export const useWorkflowRun = () => {})setEdges(newEdges)- if (onNodeStarted)- onNodeStarted(params)+ if (onIterationStart)+ onIterationStart(params)},- onNodeFinished: (params) => {+ onIterationNext: (params) => {+ const {+ workflowRunningData,+ setWorkflowRunningData,+ } = workflowStore.getState()+const { data } = params+ const {+ getNodes,+ setNodes,+ } = store.getState()++ setWorkflowRunningData(produce(workflowRunningData!, (draft) => {+ const iteration = draft.tracing![draft.tracing!.length - 1]+ if (iteration.details!.length >= iterationLength)+ return++ iteration.details!.push([])+ }))++ const nodes = getNodes()+ const newNodes = produce(nodes, (draft) => {+ const currentNode = draft.find(node => node.id === data.node_id)!++ currentNode.data._iterationIndex = data.index > 0 ? data.index : 1+ })+ setNodes(newNodes)++ if (onIterationNext)+ onIterationNext(params)+ },+ onIterationFinish: (params) => {+ const { data } = params+const {workflowRunningData,setWorkflowRunningData,@@ -261,29 +420,26 @@ export const useWorkflowRun = () => {} = store.getState()const nodes = getNodes()setWorkflowRunningData(produce(workflowRunningData!, (draft) => {- const currentIndex = draft.tracing!.findIndex(trace => trace.node_id === data.node_id)-- if (currentIndex > -1 && draft.tracing) {- draft.tracing[currentIndex] = {- ...(draft.tracing[currentIndex].extras- ? { extras: draft.tracing[currentIndex].extras }- : {}),- ...data,- } as any- }+ const tracing = draft.tracing!+ tracing[tracing.length - 1] = {+ ...tracing[tracing.length - 1],+ ...data,+ status: NodeRunningStatus.Succeeded,+ } as any}))+ isInIteration = falseconst newNodes = produce(nodes, (draft) => {const currentNode = draft.find(node => node.id === data.node_id)!- currentNode.data._runningStatus = data.status as any+ currentNode.data._runningStatus = data.status})setNodes(newNodes)prevNodeId = data.node_id- if (onNodeFinished)- onNodeFinished(params)+ if (onIterationFinish)+ onIterationFinish(params)},onTextChunk: (params) => {const { data: { text } } = paramsdiff --git a/web/app/components/workflow/hooks/use-workflow.ts b/web/app/components/workflow/hooks/use-workflow.tsindex bec457d0ef5..d7759eb998d 100644--- a/web/app/components/workflow/hooks/use-workflow.ts+++ b/web/app/components/workflow/hooks/use-workflow.ts@@ -21,6 +21,7 @@ import {getLayoutByDagre,} from '../utils'import type {+ Edge,Node,ValueSelector,} from '../types'@@ -33,7 +34,6 @@ import {useWorkflowStore,} from '../store'import {- AUTO_LAYOUT_OFFSET,SUPPORT_OUTPUT_VARS_NODE,} from '../constants'import { findUsedVarNodes, getNodeOutputVars, updateNodeVars } from '../nodes/_base/components/variable/utils'@@ -51,8 +51,10 @@ import type { FetchWorkflowDraftResponse } from '@/types/workflow'import {fetchAllBuiltInTools,fetchAllCustomTools,+ fetchAllWorkflowTools,} from '@/service/tools'import I18n from '@/context/i18n'+import { CollectionType } from '@/app/components/tools/types'export const useIsChatMode = () => {const appDetail = useAppStore(s => s.appDetail)@@ -83,13 +85,31 @@ export const useWorkflow = () => {const { setViewport } = reactflowconst nodes = getNodes()const layout = getLayoutByDagre(nodes, edges)+ const rankMap = {} as Record<string, Node>++ nodes.forEach((node) => {+ if (!node.parentId) {+ const rank = layout.node(node.id).rank!++ if (!rankMap[rank]) {+ rankMap[rank] = node+ }+ else {+ if (rankMap[rank].position.y > node.position.y)+ rankMap[rank] = node+ }+ }+ })const newNodes = produce(nodes, (draft) => {draft.forEach((node) => {- const nodeWithPosition = layout.node(node.id)- node.position = {- x: nodeWithPosition.x + AUTO_LAYOUT_OFFSET.x,- y: nodeWithPosition.y + AUTO_LAYOUT_OFFSET.y,+ if (!node.parentId) {+ const nodeWithPosition = layout.node(node.id)++ node.position = {+ x: nodeWithPosition.x - node.width! / 2,+ y: nodeWithPosition.y - node.height! / 2 + rankMap[nodeWithPosition.rank!].height! / 2,+ }}})})@@ -111,7 +131,11 @@ export const useWorkflow = () => {edges,} = store.getState()const nodes = getNodes()- const startNode = nodes.find(node => node.data.type === BlockEnum.Start)+ let startNode = nodes.find(node => node.data.type === BlockEnum.Start)+ const currentNode = nodes.find(node => node.id === nodeId)++ if (currentNode?.parentId)+ startNode = nodes.find(node => node.parentId === currentNode.parentId && node.data.isIterationStart)if (!startNode)return []@@ -145,21 +169,31 @@ export const useWorkflow = () => {})}, [store])- const getBeforeNodesInSameBranch = useCallback((nodeId: string) => {+ const getBeforeNodesInSameBranch = useCallback((nodeId: string, newNodes?: Node[], newEdges?: Edge[]) => {const {getNodes,edges,} = store.getState()- const nodes = getNodes()+ const nodes = newNodes || getNodes()const currentNode = nodes.find(node => node.id === nodeId)+const list: Node[] = []if (!currentNode)return list+ if (currentNode.parentId) {+ const parentNode = nodes.find(node => node.id === currentNode.parentId)+ if (parentNode) {+ const parentList = getBeforeNodesInSameBranch(parentNode.id)++ list.push(...parentList)+ }+ }+const traverse = (root: Node, callback: (node: Node) => void) => {if (root) {- const incomers = getIncomers(root, nodes, edges)+ const incomers = getIncomers(root, nodes, newEdges || edges)if (incomers.length) {incomers.forEach((node) => {@@ -185,6 +219,21 @@ export const useWorkflow = () => {return []}, [store])+ const getBeforeNodesInSameBranchIncludeParent = useCallback((nodeId: string, newNodes?: Node[], newEdges?: Edge[]) => {+ const nodes = getBeforeNodesInSameBranch(nodeId, newNodes, newEdges)+ const {+ getNodes,+ } = store.getState()+ const allNodes = getNodes()+ const node = allNodes.find(n => n.id === nodeId)+ const parentNodeId = node?.parentId+ const parentNode = allNodes.find(n => n.id === parentNodeId)+ if (parentNode)+ nodes.push(parentNode)++ return nodes+ }, [getBeforeNodesInSameBranch, store])+const getAfterNodesInSameBranch = useCallback((nodeId: string) => {const {getNodes,@@ -227,11 +276,19 @@ export const useWorkflow = () => {return getIncomers(node, nodes, edges)}, [store])+ const getIterationNodeChildren = useCallback((nodeId: string) => {+ const {+ getNodes,+ } = store.getState()+ const nodes = getNodes()++ return nodes.filter(node => node.parentId === nodeId)+ }, [store])+const handleOutVarRenameChange = useCallback((nodeId: string, oldValeSelector: ValueSelector, newVarSelector: ValueSelector) => {const { getNodes, setNodes } = store.getState()const afterNodes = getAfterNodesInSameBranch(nodeId)const effectNodes = findUsedVarNodes(oldValeSelector, afterNodes)- // console.log(effectNodes)if (effectNodes.length > 0) {const newNodes = getNodes().map((node) => {if (effectNodes.find(n => n.id === node.id))@@ -285,9 +342,13 @@ export const useWorkflow = () => {const sourceNode: Node = nodes.find(node => node.id === source)!const targetNode: Node = nodes.find(node => node.id === target)!+ if (targetNode.data.isIterationStart)+ return false+if (sourceNode && targetNode) {const sourceNodeAvailableNextNodes = nodesExtraData[sourceNode.data.type].availableNextNodesconst targetNodeAvailablePrevNodes = [...nodesExtraData[targetNode.data.type].availablePrevNodes, BlockEnum.Start]+if (!sourceNodeAvailableNextNodes.includes(targetNode.data.type))return false@@ -338,6 +399,7 @@ export const useWorkflow = () => {handleLayout,getTreeLeafNodes,getBeforeNodesInSameBranch,+ getBeforeNodesInSameBranchIncludeParent,getAfterNodesInSameBranch,handleOutVarRenameChange,isVarUsedInNodes,@@ -347,6 +409,7 @@ export const useWorkflow = () => {formatTimeFromNow,getNode,getBeforeNodeById,+ getIterationNodeChildren,enableShortcuts,disableShortcuts,}@@ -370,6 +433,13 @@ export const useFetchToolsData = () => {customTools: customTools || [],})}+ if (type === 'workflow') {+ const workflowTools = await fetchAllWorkflowTools()++ workflowStore.setState({+ workflowTools: workflowTools || [],+ })+ }}, [workflowStore])return {@@ -448,11 +518,14 @@ export const useWorkflowInit = () => {handleFetchPreloadData()handleFetchAllTools('builtin')handleFetchAllTools('custom')+ handleFetchAllTools('workflow')}, [handleFetchPreloadData, handleFetchAllTools])useEffect(() => {- if (data)+ if (data) {workflowStore.getState().setDraftUpdatedAt(data.updated_at)+ workflowStore.getState().setToolPublished(data.tool_published)+ }}, [data, workflowStore])return {@@ -499,14 +572,42 @@ export const useNodesReadOnly = () => {export const useToolIcon = (data: Node['data']) => {const buildInTools = useStore(s => s.buildInTools)const customTools = useStore(s => s.customTools)+ const workflowTools = useStore(s => s.workflowTools)const toolIcon = useMemo(() => {if (data.type === BlockEnum.Tool) {- if (data.provider_type === 'builtin')- return buildInTools.find(toolWithProvider => toolWithProvider.id === data.provider_id)?.icon-- return customTools.find(toolWithProvider => toolWithProvider.id === data.provider_id)?.icon+ let targetTools = buildInTools+ if (data.provider_type === CollectionType.builtIn)+ targetTools = buildInTools+ else if (data.provider_type === CollectionType.custom)+ targetTools = customTools+ else+ targetTools = workflowTools+ return targetTools.find(toolWithProvider => toolWithProvider.id === data.provider_id)?.icon}- }, [data, buildInTools, customTools])+ }, [data, buildInTools, customTools, workflowTools])return toolIcon}++export const useIsNodeInIteration = (iterationId: string) => {+ const store = useStoreApi()++ const isNodeInIteration = useCallback((nodeId: string) => {+ const {+ getNodes,+ } = store.getState()+ const nodes = getNodes()+ const node = nodes.find(node => node.id === nodeId)++ if (!node)+ return false++ if (node.parentId === iterationId)+ return true++ return false+ }, [iterationId, store])+ return {+ isNodeInIteration,+ }+}diff --git a/web/app/components/workflow/index.tsx b/web/app/components/workflow/index.tsxindex 0ad8e7b4f30..74890f50b2e 100644--- a/web/app/components/workflow/index.tsx+++ b/web/app/components/workflow/index.tsx@@ -64,11 +64,15 @@ import {initialEdges,initialNodes,} from './utils'-import { WORKFLOW_DATA_UPDATE } from './constants'+import {+ ITERATION_CHILDREN_Z_INDEX,+ WORKFLOW_DATA_UPDATE,+} from './constants'import Loading from '@/app/components/base/loading'import { FeaturesProvider } from '@/app/components/base/features'import type { Features as FeaturesData } from '@/app/components/base/features/types'import { useEventEmitterContextContext } from '@/context/event-emitter'+import Confirm from '@/app/components/base/confirm/common'const nodeTypes = {custom: CustomNode,@@ -94,6 +98,8 @@ const Workflow: FC<WorkflowProps> = memo(({const showFeaturesPanel = useStore(state => state.showFeaturesPanel)const controlMode = useStore(s => s.controlMode)const nodeAnimation = useStore(s => s.nodeAnimation)+ const showConfirm = useStore(s => s.showConfirm)+ const { setShowConfirm } = workflowStore.getState()const {handleSyncWorkflowDraft,syncWorkflowDraftWhenPageClose,@@ -227,6 +233,18 @@ const Workflow: FC<WorkflowProps> = memo(({<PanelContextmenu /><NodeContextmenu /><HelpLine />+ {+ !!showConfirm && (+ <Confirm+ isShow+ onCancel={() => setShowConfirm(undefined)}+ onConfirm={showConfirm.onConfirm}+ title={showConfirm.title}+ desc={showConfirm.desc}+ confirmWrapperClassName='!z-[11]'+ />+ )+ }<ReactFlownodeTypes={nodeTypes}edgeTypes={edgeTypes}@@ -250,6 +268,7 @@ const Workflow: FC<WorkflowProps> = memo(({onSelectionDrag={handleSelectionDrag}onPaneContextMenu={handlePaneContextMenu}connectionLineComponent={CustomConnectionLine}+ connectionLineContainerStyle={{ zIndex: ITERATION_CHILDREN_Z_INDEX }}defaultViewport={viewport}multiSelectionKeyCode={null}deleteKeyCode={null}diff --git a/web/app/components/workflow/nodes/_base/components/add-variable-popup-with-position.tsx b/web/app/components/workflow/nodes/_base/components/add-variable-popup-with-position.tsxnew file mode 100644index 00000000000..8ae7bf9da50--- /dev/null+++ b/web/app/components/workflow/nodes/_base/components/add-variable-popup-with-position.tsx@@ -0,0 +1,123 @@+import {+ memo,+ useCallback,+ useMemo,+ useRef,+} from 'react'+import { useClickAway } from 'ahooks'+import { useTranslation } from 'react-i18next'+import { useStore } from '../../../store'+import {+ useIsChatMode,+ useNodeDataUpdate,+ useWorkflow,+} from '../../../hooks'+import type {+ ValueSelector,+ Var,+ VarType,+} from '../../../types'+import { useVariableAssigner } from '../../variable-assigner/hooks'+import { filterVar } from '../../variable-assigner/utils'+import AddVariablePopup from './add-variable-popup'+import { toNodeAvailableVars } from '@/app/components/workflow/nodes/_base/components/variable/utils'++type AddVariablePopupWithPositionProps = {+ nodeId: string+ nodeData: any+}+const AddVariablePopupWithPosition = ({+ nodeId,+ nodeData,+}: AddVariablePopupWithPositionProps) => {+ const { t } = useTranslation()+ const ref = useRef(null)+ const showAssignVariablePopup = useStore(s => s.showAssignVariablePopup)+ const setShowAssignVariablePopup = useStore(s => s.setShowAssignVariablePopup)+ const { handleNodeDataUpdate } = useNodeDataUpdate()+ const { handleAddVariableInAddVariablePopupWithPosition } = useVariableAssigner()+ const isChatMode = useIsChatMode()+ const { getBeforeNodesInSameBranch } = useWorkflow()++ const outputType = useMemo(() => {+ if (!showAssignVariablePopup)+ return ''++ if (showAssignVariablePopup.variableAssignerNodeHandleId === 'target')+ return showAssignVariablePopup.variableAssignerNodeData.output_type++ const group = showAssignVariablePopup.variableAssignerNodeData.advanced_settings?.groups.find(group => group.groupId === showAssignVariablePopup.variableAssignerNodeHandleId)+ return group?.output_type || ''+ }, [showAssignVariablePopup])+ const availableVars = useMemo(() => {+ if (!showAssignVariablePopup)+ return []++ return toNodeAvailableVars({+ parentNode: showAssignVariablePopup.parentNode,+ t,+ beforeNodes: [+ ...getBeforeNodesInSameBranch(showAssignVariablePopup.nodeId),+ {+ id: showAssignVariablePopup.nodeId,+ data: showAssignVariablePopup.nodeData,+ } as any,+ ],+ isChatMode,+ filterVar: filterVar(outputType as VarType),+ })+ }, [getBeforeNodesInSameBranch, isChatMode, showAssignVariablePopup, t, outputType])++ useClickAway(() => {+ if (nodeData._holdAddVariablePopup) {+ handleNodeDataUpdate({+ id: nodeId,+ data: {+ _holdAddVariablePopup: false,+ },+ })+ }+ else {+ handleNodeDataUpdate({+ id: nodeId,+ data: {+ _showAddVariablePopup: false,+ },+ })+ setShowAssignVariablePopup(undefined)+ }+ }, ref)++ const handleAddVariable = useCallback((value: ValueSelector, varDetail: Var) => {+ if (showAssignVariablePopup) {+ handleAddVariableInAddVariablePopupWithPosition(+ showAssignVariablePopup.nodeId,+ showAssignVariablePopup.variableAssignerNodeId,+ showAssignVariablePopup.variableAssignerNodeHandleId,+ value,+ varDetail,+ )+ }+ }, [showAssignVariablePopup, handleAddVariableInAddVariablePopupWithPosition])++ if (!showAssignVariablePopup)+ return null++ return (+ <div+ className='absolute z-10'+ style={{+ left: showAssignVariablePopup.x,+ top: showAssignVariablePopup.y,+ }}+ ref={ref}+ >+ <AddVariablePopup+ availableVars={availableVars}+ onSelect={handleAddVariable}+ />+ </div>+ )+}++export default memo(AddVariablePopupWithPosition)diff --git a/web/app/components/workflow/nodes/_base/components/add-variable-popup.tsx b/web/app/components/workflow/nodes/_base/components/add-variable-popup.tsxnew file mode 100644index 00000000000..d44a644864e--- /dev/null+++ b/web/app/components/workflow/nodes/_base/components/add-variable-popup.tsx@@ -0,0 +1,36 @@+import { memo } from 'react'+import { useTranslation } from 'react-i18next'+import VarReferenceVars from '@/app/components/workflow/nodes/_base/components/variable/var-reference-vars'+import type {+ NodeOutPutVar,+ ValueSelector,+ Var,+} from '@/app/components/workflow/types'++export type AddVariablePopupProps = {+ availableVars: NodeOutPutVar[]+ onSelect: (value: ValueSelector, item: Var) => void+}+export const AddVariablePopup = ({+ availableVars,+ onSelect,+}: AddVariablePopupProps) => {+ const { t } = useTranslation()++ return (+ <div className='w-[240px] bg-white border-[0.5px] border-gray-200 rounded-lg shadow-lg'>+ <div className='flex items-center px-4 h-[34px] text-[13px] font-semibold text-gray-700 border-b-[0.5px] border-b-gray-200'>+ {t('workflow.nodes.variableAssigner.setAssignVariable')}+ </div>+ <div className='p-1'>+ <VarReferenceVars+ hideSearch+ vars={availableVars}+ onChange={onSelect}+ />+ </div>+ </div>+ )+}++export default memo(AddVariablePopup)diff --git a/web/app/components/workflow/nodes/_base/components/before-run-form/form-item.tsx b/web/app/components/workflow/nodes/_base/components/before-run-form/form-item.tsxindex 74da485495a..7e50ddcc97a 100644--- a/web/app/components/workflow/nodes/_base/components/before-run-form/form-item.tsx+++ b/web/app/components/workflow/nodes/_base/components/before-run-form/form-item.tsx@@ -7,6 +7,7 @@ import type { InputVar } from '../../../../types'import { BlockEnum, InputVarType } from '../../../../types'import CodeEditor from '../editor/code-editor'import { CodeLanguage } from '../../../code/types'+import TextEditor from '../editor/text-editor'import Select from '@/app/components/base/select'import TextGenerationImageUploader from '@/app/components/base/image-uploader/text-generation-image-uploader'import { Resolution } from '@/types/app'@@ -34,7 +35,7 @@ const FormItem: FC<Props> = ({const { t } = useTranslation()const { type } = payloadconst fileSettings = useFeatures(s => s.features.file)- const handleContextItemChange = useCallback((index: number) => {+ const handleArrayItemChange = useCallback((index: number) => {return (newValue: any) => {const newValues = produce(value, (draft: any) => {draft[index] = newValue@@ -43,7 +44,7 @@ const FormItem: FC<Props> = ({}}, [value, onChange])- const handleContextItemRemove = useCallback((index: number) => {+ const handleArrayItemRemove = useCallback((index: number) => {return () => {const newValues = produce(value, (draft: any) => {draft.splice(index, 1)@@ -77,9 +78,13 @@ const FormItem: FC<Props> = ({}return ''})()++ const isArrayLikeType = [InputVarType.contexts, InputVarType.iterator].includes(type)+ const isContext = type === InputVarType.contexts+ const isIterator = type === InputVarType.iteratorreturn (<div className={`${className}`}>- {type !== InputVarType.contexts && <div className='h-8 leading-8 text-[13px] font-medium text-gray-700 truncate'>{typeof payload.label === 'object' ? nodeKey : payload.label}</div>}+ {!isArrayLikeType && <div className='h-8 leading-8 text-[13px] font-medium text-gray-700 truncate'>{typeof payload.label === 'object' ? nodeKey : payload.label}</div>}<div className='grow'>{type === InputVarType.textInput && (@@ -160,7 +165,7 @@ const FormItem: FC<Props> = ({}{- type === InputVarType.contexts && (+ isContext && (<div className='space-y-2'>{(value || []).map((item: any, index: number) => (<CodeEditor@@ -170,13 +175,37 @@ const FormItem: FC<Props> = ({headerRight={(value as any).length > 1? (<Trash03- onClick={handleContextItemRemove(index)}+ onClick={handleArrayItemRemove(index)}className='mr-1 w-3.5 h-3.5 text-gray-500 cursor-pointer'/>): undefined}language={CodeLanguage.json}- onChange={handleContextItemChange(index)}+ onChange={handleArrayItemChange(index)}+ />+ ))}+ </div>+ )+ }++ {+ isIterator && (+ <div className='space-y-2'>+ {(value || []).map((item: any, index: number) => (+ <TextEditor+ key={index}+ isInNode+ value={item}+ title={<span>{t('appDebug.variableConig.content')} {index + 1} </span>}+ onChange={handleArrayItemChange(index)}+ headerRight={+ (value as any).length > 1+ ? (<Trash03+ onClick={handleArrayItemRemove(index)}+ className='mr-1 w-3.5 h-3.5 text-gray-500 cursor-pointer'+ />)+ : undefined+ }/>))}</div>diff --git a/web/app/components/workflow/nodes/_base/components/before-run-form/form.tsx b/web/app/components/workflow/nodes/_base/components/before-run-form/form.tsxindex 22aaaf6a130..40aee2a0e5e 100644--- a/web/app/components/workflow/nodes/_base/components/before-run-form/form.tsx+++ b/web/app/components/workflow/nodes/_base/components/before-run-form/form.tsx@@ -32,20 +32,22 @@ const Form: FC<Props> = ({onChange(newValues)}}, [values, onChange])-+ const isArrayLikeType = [InputVarType.contexts, InputVarType.iterator].includes(inputs[0]?.type)+ const isContext = inputs[0]?.type === InputVarType.contextsconst handleAddContext = useCallback(() => {const newValues = produce(values, (draft: any) => {const key = inputs[0].variable- draft[key].push(RETRIEVAL_OUTPUT_STRUCT)+ draft[key].push(isContext ? RETRIEVAL_OUTPUT_STRUCT : '')})onChange(newValues)- }, [values, onChange, inputs])+ }, [values, onChange, inputs, isContext])+return (<div className={cn(className, 'space-y-2')}>{label && (<div className='mb-1 flex items-center justify-between'><div className='flex items-center h-6 text-xs font-medium text-gray-500 uppercase'>{label}</div>- {inputs[0]?.type === InputVarType.contexts && (+ {isArrayLikeType && (<AddButton onClick={handleAddContext} />)}</div>diff --git a/web/app/components/workflow/nodes/_base/components/editor/base.tsx b/web/app/components/workflow/nodes/_base/components/editor/base.tsxindex 59e01d2ad91..5877a01be38 100644--- a/web/app/components/workflow/nodes/_base/components/editor/base.tsx+++ b/web/app/components/workflow/nodes/_base/components/editor/base.tsx@@ -46,6 +46,9 @@ const Base: FC<Props> = ({const handleCopy = useCallback(() => {copy(value)setIsCopied(true)+ setTimeout(() => {+ setIsCopied(false)+ }, 2000)}, [value])return (diff --git a/web/app/components/workflow/nodes/_base/components/field.tsx b/web/app/components/workflow/nodes/_base/components/field.tsxindex 8a4dcd70e77..b47d66c4a8b 100644--- a/web/app/components/workflow/nodes/_base/components/field.tsx+++ b/web/app/components/workflow/nodes/_base/components/field.tsx@@ -3,11 +3,14 @@ import type { FC } from 'react'import React from 'react'import cn from 'classnames'import { useBoolean } from 'ahooks'+import type { DefaultTFuncReturn } from 'i18next'import { HelpCircle } from '@/app/components/base/icons/src/vender/line/general'import TooltipPlus from '@/app/components/base/tooltip-plus'import { ChevronRight } from '@/app/components/base/icons/src/vender/line/arrows'+type Props = {- title: string+ className?: string+ title: JSX.Element | string | DefaultTFuncReturntooltip?: stringsupportFold?: booleanchildren?: JSX.Element | string | null@@ -16,6 +19,7 @@ type Props = {}const Filed: FC<Props> = ({+ className,title,tooltip,children,@@ -27,7 +31,7 @@ const Filed: FC<Props> = ({toggle: toggleFold,}] = useBoolean(true)return (- <div className={cn(inline && 'flex justify-between items-center', supportFold && 'cursor-pointer')}>+ <div className={cn(className, inline && 'flex justify-between items-center', supportFold && 'cursor-pointer')}><divonClick={() => supportFold && toggleFold()}className='flex justify-between items-center'>diff --git a/web/app/components/workflow/nodes/_base/components/list-no-data-placeholder.tsx b/web/app/components/workflow/nodes/_base/components/list-no-data-placeholder.tsxnew file mode 100644index 00000000000..4ec9d27f506--- /dev/null+++ b/web/app/components/workflow/nodes/_base/components/list-no-data-placeholder.tsx@@ -0,0 +1,18 @@+'use client'+import type { FC } from 'react'+import React from 'react'++type Props = {+ children: React.ReactNode+}++const ListNoDataPlaceholder: FC<Props> = ({+ children,+}) => {+ return (+ <div className='flex rounded-md bg-gray-50 items-center min-h-[42px] justify-center leading-[18px] text-xs font-normal text-gray-500'>+ {children}+ </div>+ )+}+export default React.memo(ListNoDataPlaceholder)diff --git a/web/app/components/workflow/nodes/_base/components/next-step/item.tsx b/web/app/components/workflow/nodes/_base/components/next-step/item.tsxindex 865d8b6cc92..2f4124fd2c5 100644--- a/web/app/components/workflow/nodes/_base/components/next-step/item.tsx+++ b/web/app/components/workflow/nodes/_base/components/next-step/item.tsx@@ -11,7 +11,7 @@ import type {import BlockIcon from '@/app/components/workflow/block-icon'import BlockSelector from '@/app/components/workflow/block-selector'import {- useNodesExtraData,+ useAvailableBlocks,useNodesInteractions,useNodesReadOnly,useToolIcon,@@ -33,10 +33,12 @@ const Item = ({const { t } = useTranslation()const { handleNodeChange } = useNodesInteractions()const { nodesReadOnly } = useNodesReadOnly()- const nodesExtraData = useNodesExtraData()const toolIcon = useToolIcon(data)- const availablePrevNodes = nodesExtraData[data.type].availablePrevNodes- const availableNextNodes = nodesExtraData[data.type].availableNextNodes+ const {+ availablePrevBlocks,+ availableNextBlocks,+ } = useAvailableBlocks(data.type, data.isInIteration)+const handleSelect = useCallback<OnSelectBlock>((type, toolDefaultValue) => {handleNodeChange(nodeId, type, sourceHandle, toolDefaultValue)}, [nodeId, sourceHandle, handleNodeChange])@@ -84,7 +86,7 @@ const Item = ({}}trigger={renderTrigger}popupClassName='!w-[328px]'- availableBlocksTypes={intersection(availablePrevNodes, availableNextNodes).filter(item => item !== data.type)}+ availableBlocksTypes={intersection(availablePrevBlocks, availableNextBlocks).filter(item => item !== data.type)}/>)}diff --git a/web/app/components/workflow/nodes/_base/components/node-handle.tsx b/web/app/components/workflow/nodes/_base/components/node-handle.tsxindex 0c14cbaedf5..3885b6805a7 100644--- a/web/app/components/workflow/nodes/_base/components/node-handle.tsx+++ b/web/app/components/workflow/nodes/_base/components/node-handle.tsx@@ -14,7 +14,7 @@ import type { Node } from '../../../types'import BlockSelector from '../../../block-selector'import type { ToolDefaultValue } from '../../../block-selector/types'import {- useNodesExtraData,+ useAvailableBlocks,useNodesInteractions,useNodesReadOnly,} from '../../../hooks'@@ -35,11 +35,12 @@ export const NodeTargetHandle = memo(({}: NodeHandleProps) => {const [open, setOpen] = useState(false)const { handleNodeAdd } = useNodesInteractions()- const nodesExtraData = useNodesExtraData()const { getNodesReadOnly } = useNodesReadOnly()const connected = data._connectedTargetHandleIds?.includes(handleId)- const availablePrevNodes = nodesExtraData[data.type].availablePrevNodes- const isConnectable = !!availablePrevNodes.length+ const { availablePrevBlocks } = useAvailableBlocks(data.type, data.isInIteration)+ const isConnectable = !!availablePrevBlocks.length && (+ !data.isIterationStart+ )const handleOpenChange = useCallback((v: boolean) => {setOpen(v)@@ -80,7 +81,7 @@ export const NodeTargetHandle = memo(({onClick={handleHandleClick}>{- !connected && isConnectable && !data._isInvalidConnection && !getNodesReadOnly() && (+ !connected && isConnectable && !getNodesReadOnly() && (<BlockSelectoropen={open}onOpenChange={handleOpenChange}@@ -94,7 +95,7 @@ export const NodeTargetHandle = memo(({${data.selected && '!flex'}${open && '!flex'}`}- availableBlocksTypes={availablePrevNodes}+ availableBlocksTypes={availablePrevBlocks}/>)}@@ -112,12 +113,14 @@ export const NodeSourceHandle = memo(({nodeSelectorClassName,}: NodeHandleProps) => {const notInitialWorkflow = useStore(s => s.notInitialWorkflow)+ const connectingNodePayload = useStore(s => s.connectingNodePayload)const [open, setOpen] = useState(false)const { handleNodeAdd } = useNodesInteractions()- const nodesExtraData = useNodesExtraData()const { getNodesReadOnly } = useNodesReadOnly()- const availableNextNodes = nodesExtraData[data.type].availableNextNodes- const isConnectable = !!availableNextNodes.length+ const { availableNextBlocks } = useAvailableBlocks(data.type, data.isInIteration)+ const isUnConnectable = !availableNextBlocks.length || ((connectingNodePayload?.nodeType === BlockEnum.VariableAssigner || connectingNodePayload?.nodeType === BlockEnum.VariableAggregator) && connectingNodePayload?.handleType === 'target')+ const isConnectable = !isUnConnectable+const connected = data._connectedSourceHandleIds?.includes(handleId)const handleOpenChange = useCallback((v: boolean) => {setOpen(v)@@ -162,7 +165,7 @@ export const NodeSourceHandle = memo(({onClick={handleHandleClick}>{- !connected && isConnectable && !data._isInvalidConnection && !getNodesReadOnly() && (+ !connected && isConnectable && !getNodesReadOnly() && (<BlockSelectoropen={open}onOpenChange={handleOpenChange}@@ -175,7 +178,7 @@ export const NodeSourceHandle = memo(({${data.selected && '!flex'}${open && '!flex'}`}- availableBlocksTypes={availableNextNodes}+ availableBlocksTypes={availableNextBlocks}/>)}diff --git a/web/app/components/workflow/nodes/_base/components/node-resizer.tsx b/web/app/components/workflow/nodes/_base/components/node-resizer.tsxnew file mode 100644index 00000000000..377f5f4c2d8--- /dev/null+++ b/web/app/components/workflow/nodes/_base/components/node-resizer.tsx@@ -0,0 +1,51 @@+import {+ memo,+ useCallback,+} from 'react'+import cn from 'classnames'+import type { OnResize } from 'reactflow'+import { NodeResizeControl } from 'reactflow'+import { useNodesInteractions } from '../../../hooks'+import type { CommonNodeType } from '../../../types'++const Icon = () => {+ return (+ <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16" fill="none">+ <path d="M5.19009 11.8398C8.26416 10.6196 10.7144 8.16562 11.9297 5.08904" stroke="black" strokeOpacity="0.16" strokeWidth="2" strokeLinecap="round"/>+ </svg>+ )+}++type NodeResizerProps = {+ nodeId: string+ nodeData: CommonNodeType+}+const NodeResizer = ({+ nodeId,+ nodeData,+}: NodeResizerProps) => {+ const { handleNodeResize } = useNodesInteractions()++ const handleResize = useCallback<OnResize>((_, params) => {+ handleNodeResize(nodeId, params)+ }, [nodeId, handleNodeResize])++ return (+ <div className={cn(+ 'hidden group-hover:block',+ nodeData.selected && '!block',+ )}>+ <NodeResizeControl+ position='bottom-right'+ className='!border-none !bg-transparent'+ onResize={handleResize}+ minWidth={272}+ minHeight={176}+ >+ <div className='absolute bottom-[1px] right-[1px]'><Icon /></div>+ </NodeResizeControl>+ </div>+ )+}++export default memo(NodeResizer)diff --git a/web/app/components/workflow/nodes/_base/components/panel-operator/change-block.tsx b/web/app/components/workflow/nodes/_base/components/panel-operator/change-block.tsxindex 0826422d72d..debeb9a7ce8 100644--- a/web/app/components/workflow/nodes/_base/components/panel-operator/change-block.tsx+++ b/web/app/components/workflow/nodes/_base/components/panel-operator/change-block.tsx@@ -7,38 +7,39 @@ import { useTranslation } from 'react-i18next'import { intersection } from 'lodash-es'import BlockSelector from '@/app/components/workflow/block-selector'import {- useNodesExtraData,+ useAvailableBlocks,useNodesInteractions,} from '@/app/components/workflow/hooks'import type {- BlockEnum,+ Node,OnSelectBlock,} from '@/app/components/workflow/types'type ChangeBlockProps = {nodeId: string- nodeType: BlockEnum+ nodeData: Node['data']sourceHandle: string}const ChangeBlock = ({nodeId,- nodeType,+ nodeData,sourceHandle,}: ChangeBlockProps) => {const { t } = useTranslation()const { handleNodeChange } = useNodesInteractions()- const nodesExtraData = useNodesExtraData()- const availablePrevNodes = nodesExtraData[nodeType].availablePrevNodes- const availableNextNodes = nodesExtraData[nodeType].availableNextNodes+ const {+ availablePrevBlocks,+ availableNextBlocks,+ } = useAvailableBlocks(nodeData.type, nodeData.isInIteration)const availableNodes = useMemo(() => {- if (availableNextNodes.length && availableNextNodes.length)- return intersection(availablePrevNodes, availableNextNodes)- else if (availablePrevNodes.length)- return availablePrevNodes+ if (availablePrevBlocks.length && availableNextBlocks.length)+ return intersection(availablePrevBlocks, availableNextBlocks)+ else if (availablePrevBlocks.length)+ return availablePrevBlockselse- return availableNextNodes- }, [availablePrevNodes, availableNextNodes])+ return availableNextBlocks+ }, [availablePrevBlocks, availableNextBlocks])const handleSelect = useCallback<OnSelectBlock>((type, toolDefaultValue) => {handleNodeChange(nodeId, type, sourceHandle, toolDefaultValue)diff --git a/web/app/components/workflow/nodes/_base/components/panel-operator/panel-operator-popup.tsx b/web/app/components/workflow/nodes/_base/components/panel-operator/panel-operator-popup.tsxindex 0a0fad3a4d8..6f4ad867b6b 100644--- a/web/app/components/workflow/nodes/_base/components/panel-operator/panel-operator-popup.tsx+++ b/web/app/components/workflow/nodes/_base/components/panel-operator/panel-operator-popup.tsx@@ -20,6 +20,7 @@ import ShortcutsName from '@/app/components/workflow/shortcuts-name'import type { Node } from '@/app/components/workflow/types'import { BlockEnum } from '@/app/components/workflow/types'import { useGetLanguage } from '@/context/i18n'+import { CollectionType } from '@/app/components/tools/types'type PanelOperatorPopupProps = {id: string@@ -46,28 +47,35 @@ const PanelOperatorPopup = ({const nodesExtraData = useNodesExtraData()const buildInTools = useStore(s => s.buildInTools)const customTools = useStore(s => s.customTools)+ const workflowTools = useStore(s => s.workflowTools)const edge = edges.find(edge => edge.target === id)const author = useMemo(() => {if (data.type !== BlockEnum.Tool)return nodesExtraData[data.type].author- if (data.provider_type === 'builtin')+ if (data.provider_type === CollectionType.builtIn)return buildInTools.find(toolWithProvider => toolWithProvider.id === data.provider_id)?.author+ if (data.provider_type === CollectionType.workflow)+ return workflowTools.find(toolWithProvider => toolWithProvider.id === data.provider_id)?.author+return customTools.find(toolWithProvider => toolWithProvider.id === data.provider_id)?.author- }, [data, nodesExtraData, buildInTools, customTools])+ }, [data, nodesExtraData, buildInTools, customTools, workflowTools])const about = useMemo(() => {if (data.type !== BlockEnum.Tool)return nodesExtraData[data.type].about- if (data.provider_type === 'builtin')+ if (data.provider_type === CollectionType.builtIn)return buildInTools.find(toolWithProvider => toolWithProvider.id === data.provider_id)?.description[language]+ if (data.provider_type === CollectionType.workflow)+ return workflowTools.find(toolWithProvider => toolWithProvider.id === data.provider_id)?.description[language]+return customTools.find(toolWithProvider => toolWithProvider.id === data.provider_id)?.description[language]- }, [data, nodesExtraData, language, buildInTools, customTools])+ }, [data, nodesExtraData, language, buildInTools, customTools, workflowTools])- const showChangeBlock = data.type !== BlockEnum.Start && !nodesReadOnly+ const showChangeBlock = data.type !== BlockEnum.Start && !nodesReadOnly && data.type !== BlockEnum.Iterationreturn (<div className='w-[240px] border-[0.5px] border-gray-200 rounded-lg shadow-xl bg-white'>@@ -97,7 +105,7 @@ const PanelOperatorPopup = ({showChangeBlock && (<ChangeBlocknodeId={id}- nodeType={data.type}+ nodeData={data}sourceHandle={edge?.sourceHandle || 'source'}/>)diff --git a/web/app/components/workflow/nodes/_base/components/readonly-input-with-select-var.tsx b/web/app/components/workflow/nodes/_base/components/readonly-input-with-select-var.tsxindex bb838a23b4e..2138ea8f528 100644--- a/web/app/components/workflow/nodes/_base/components/readonly-input-with-select-var.tsx+++ b/web/app/components/workflow/nodes/_base/components/readonly-input-with-select-var.tsx@@ -18,8 +18,8 @@ const ReadonlyInputWithSelectVar: FC<Props> = ({nodeId,value,}) => {- const { getBeforeNodesInSameBranch } = useWorkflow()- const availableNodes = getBeforeNodesInSameBranch(nodeId)+ const { getBeforeNodesInSameBranchIncludeParent } = useWorkflow()+ const availableNodes = getBeforeNodesInSameBranchIncludeParent(nodeId)const startNode = availableNodes.find((node: any) => {return node.data.type === BlockEnum.Start})diff --git a/web/app/components/workflow/nodes/_base/components/variable/utils.ts b/web/app/components/workflow/nodes/_base/components/variable/utils.tsindex d5d2c3ef60f..6545358ee41 100644--- a/web/app/components/workflow/nodes/_base/components/variable/utils.ts+++ b/web/app/components/workflow/nodes/_base/components/variable/utils.ts@@ -11,6 +11,8 @@ import type { QuestionClassifierNodeType } from '../../../question-classifier/tyimport type { HttpNodeType } from '../../../http/types'import { VarType as ToolVarType } from '../../../tool/types'import type { ToolNodeType } from '../../../tool/types'+import type { ParameterExtractorNodeType } from '../../../parameter-extractor/types'+import type { IterationNodeType } from '../../../iteration/types'import { BlockEnum, InputVarType, VarType } from '@/app/components/workflow/types'import type { StartNodeType } from '@/app/components/workflow/nodes/start/types'import type { Node, NodeOutPutVar, ValueSelector, Var } from '@/app/components/workflow/types'@@ -19,6 +21,7 @@ import {HTTP_REQUEST_OUTPUT_STRUCT,KNOWLEDGE_RETRIEVAL_OUTPUT_STRUCT,LLM_OUTPUT_STRUCT,+ PARAMETER_EXTRACTOR_COMMON_STRUCT,QUESTION_CLASSIFIER_OUTPUT_STRUCT,SUPPORT_OUTPUT_VARS_NODE,TEMPLATE_TRANSFORM_OUTPUT_STRUCT,@@ -27,6 +30,10 @@ import {import type { PromptItem } from '@/models/debug'import { VAR_REGEX } from '@/config'+export const isSystemVar = (valueSelector: ValueSelector) => {+ return valueSelector[0] === 'sys' || valueSelector[1] === 'sys'+}+const inputVarTypeToVarType = (type: InputVarType): VarType => {if (type === InputVarType.number)return VarType.number@@ -54,6 +61,7 @@ const findExceptVarInObject = (obj: any, filterVar: (payload: Var, selector: Valconst formatItem = (item: any, isChatMode: boolean, filterVar: (payload: Var, selector: ValueSelector) => boolean): NodeOutPutVar => {const { id, data } = item+const res: NodeOutPutVar = {nodeId: id,title: data.title,@@ -136,13 +144,58 @@ const formatItem = (item: any, isChatMode: boolean, filterVar: (payload: Var, secase BlockEnum.VariableAssigner: {const {output_type,+ advanced_settings,} = data as VariableAssignerNodeType- res.vars = [- {- variable: 'output',- type: output_type,- },- ]+ const isGroup = !!advanced_settings?.group_enabled+ if (!isGroup) {+ res.vars = [+ {+ variable: 'output',+ type: output_type,+ },+ ]+ }+ else {+ res.vars = advanced_settings?.groups.map((group) => {+ return {+ variable: group.group_name,+ type: VarType.object,+ children: [{+ variable: 'output',+ type: group.output_type,+ }],+ }+ })+ }+ break+ }++ case BlockEnum.VariableAggregator: {+ const {+ output_type,+ advanced_settings,+ } = data as VariableAssignerNodeType+ const isGroup = !!advanced_settings?.group_enabled+ if (!isGroup) {+ res.vars = [+ {+ variable: 'output',+ type: output_type,+ },+ ]+ }+ else {+ res.vars = advanced_settings?.groups.map((group) => {+ return {+ variable: group.group_name,+ type: VarType.object,+ children: [{+ variable: 'output',+ type: group.output_type,+ }],+ }+ })+ }break}@@ -150,6 +203,28 @@ const formatItem = (item: any, isChatMode: boolean, filterVar: (payload: Var, seres.vars = TOOL_OUTPUT_STRUCTbreak}++ case BlockEnum.ParameterExtractor: {+ res.vars = [+ ...PARAMETER_EXTRACTOR_COMMON_STRUCT,+ ...((data as ParameterExtractorNodeType).parameters || []).map((p) => {+ return {+ variable: p.name,+ type: p.type as unknown as VarType,+ }+ })]+ break+ }++ case BlockEnum.Iteration: {+ res.vars = [+ {+ variable: 'output',+ type: (data as IterationNodeType).output_type || VarType.arrayString,+ },+ ]+ break+ }}const selector = [id]@@ -183,37 +258,113 @@ export const toNodeOutputVars = (nodes: any[], isChatMode: boolean, filterVar =return res}-export const isSystemVar = (valueSelector: ValueSelector) => {- return valueSelector[0] === 'sys' || valueSelector[1] === 'sys'-}+const getIterationItemType = ({+ valueSelector,+ beforeNodesOutputVars,+}: {+ valueSelector: ValueSelector+ beforeNodesOutputVars: NodeOutPutVar[]+}): VarType => {+ const outputVarNodeId = valueSelector[0]+ const targetVar = beforeNodesOutputVars.find(v => v.nodeId === outputVarNodeId)+ if (!targetVar)+ return VarType.string-export const getNodeInfoById = (nodes: any, id: string) => {- if (!isArray(nodes))- return- return nodes.find((node: any) => node.id === id)+ let arrayType: VarType = VarType.string++ const isSystem = isSystemVar(valueSelector)+ let curr: any = targetVar.vars++ if (isSystem)+ return curr.find((v: any) => v.variable === (valueSelector).join('.'))?.type;++ (valueSelector).slice(1).forEach((key, i) => {+ const isLast = i === valueSelector.length - 2+ curr = curr?.find((v: any) => v.variable === key)+ if (isLast) {+ arrayType = curr?.type+ }+ else {+ if (curr?.type === VarType.object)+ curr = curr.children+ }+ })+ switch (arrayType as VarType) {+ case VarType.arrayString:+ return VarType.string+ case VarType.arrayNumber:+ return VarType.number+ case VarType.arrayObject:+ return VarType.object+ case VarType.array:+ return VarType.any+ case VarType.arrayFile:+ return VarType.object+ default:+ return VarType.string+ }}-export const getVarType = (value: ValueSelector, availableNodes: any[], isChatMode: boolean): VarType | undefined => {- const isSystem = isSystemVar(value)+export const getVarType = ({+ parentNode,+ valueSelector,+ isIterationItem,+ availableNodes,+ isChatMode,+ isConstant,+}:+{+ valueSelector: ValueSelector+ parentNode?: Node | null+ isIterationItem?: boolean+ availableNodes: any[]+ isChatMode: boolean+ isConstant?: boolean+}): VarType => {+ if (isConstant)+ return VarType.string++ const beforeNodesOutputVars = toNodeOutputVars(availableNodes, isChatMode)++ const isIterationInnerVar = parentNode?.data.type === BlockEnum.Iteration+ if (isIterationItem) {+ return getIterationItemType({+ valueSelector,+ beforeNodesOutputVars,+ })+ }+ if (isIterationInnerVar) {+ if (valueSelector[1] === 'item') {+ const itemType = getIterationItemType({+ valueSelector: (parentNode?.data as any).iterator_selector || [],+ beforeNodesOutputVars,+ })+ return itemType+ }+ if (valueSelector[1] === 'index')+ return VarType.number++ return VarType.string+ }+ const isSystem = isSystemVar(valueSelector)const startNode = availableNodes.find((node: any) => {return node.data.type === BlockEnum.Start})- const allOutputVars = toNodeOutputVars(availableNodes, isChatMode)- const targetVarNodeId = isSystem ? startNode?.id : value[0]- const targetVar = allOutputVars.find(v => v.nodeId === targetVarNodeId)+ const targetVarNodeId = isSystem ? startNode?.id : valueSelector[0]+ const targetVar = beforeNodesOutputVars.find(v => v.nodeId === targetVarNodeId)if (!targetVar)- return undefined+ return VarType.stringlet type: VarType = VarType.stringlet curr: any = targetVar.varsif (isSystem) {- return curr.find((v: any) => v.variable === (value as ValueSelector).join('.'))?.type+ return curr.find((v: any) => v.variable === (valueSelector as ValueSelector).join('.'))?.type}else {- (value as ValueSelector).slice(1).forEach((key, i) => {- const isLast = i === value.length - 2+ (valueSelector as ValueSelector).slice(1).forEach((key, i) => {+ const isLast = i === valueSelector.length - 2curr = curr.find((v: any) => v.variable === key)if (isLast) {type = curr?.type@@ -227,6 +378,57 @@ export const getVarType = (value: ValueSelector, availableNodes: any[], isChatMo}}+// node output vars + parent inner vars(if in iteration or other wrap node)+export const toNodeAvailableVars = ({+ parentNode,+ t,+ beforeNodes,+ isChatMode,+ filterVar,+}: {+ parentNode?: Node | null+ t?: any+ // to get those nodes output vars+ beforeNodes: Node[]+ isChatMode: boolean+ filterVar: (payload: Var, selector: ValueSelector) => boolean+}): NodeOutPutVar[] => {+ const beforeNodesOutputVars = toNodeOutputVars(beforeNodes, isChatMode, filterVar)+ const isInIteration = parentNode?.data.type === BlockEnum.Iteration+ if (isInIteration) {+ const iterationNode: any = parentNode+ const itemType = getVarType({+ parentNode: iterationNode,+ isIterationItem: true,+ valueSelector: iterationNode?.data.iterator_selector || [],+ availableNodes: beforeNodes,+ isChatMode,+ })+ const iterationVar = {+ nodeId: iterationNode?.id,+ title: t('workflow.nodes.iteration.currentIteration'),+ vars: [+ {+ variable: 'item',+ type: itemType,+ },+ {+ variable: 'index',+ type: VarType.number,+ },+ ],+ }+ beforeNodesOutputVars.unshift(iterationVar)+ }+ return beforeNodesOutputVars+}++export const getNodeInfoById = (nodes: any, id: string) => {+ if (!isArray(nodes))+ return+ return nodes.find((node: any) => node.id === id)+}+const matchNotSystemVars = (prompts: string[]) => {if (!prompts)return []@@ -326,11 +528,98 @@ export const getNodeUsedVars = (node: Node): ValueSelector[] => {case BlockEnum.VariableAssigner: {res = (data as VariableAssignerNodeType)?.variables+ break+ }++ case BlockEnum.VariableAggregator: {+ res = (data as VariableAssignerNodeType)?.variables+ break+ }++ case BlockEnum.ParameterExtractor: {+ const payload = (data as ParameterExtractorNodeType)+ res = [payload.query]+ const varInInstructions = matchNotSystemVars([payload.instruction || ''])+ res.push(...varInInstructions)+ break+ }++ case BlockEnum.Iteration: {+ res = [(data as IterationNodeType).iterator_selector]+ break}}return res || []}+// used can be used in iteration node+export const getNodeUsedVarPassToServerKey = (node: Node, valueSelector: ValueSelector): string | string[] => {+ const { data } = node+ const { type } = data+ let res: string | string[] = ''+ switch (type) {+ case BlockEnum.LLM: {+ const payload = (data as LLMNodeType)+ res = [`#${valueSelector.join('.')}#`]+ if (payload.context?.variable_selector.join('.') === valueSelector.join('.'))+ res.push('#context#')++ break+ }+ case BlockEnum.KnowledgeRetrieval: {+ res = 'query'+ break+ }+ case BlockEnum.IfElse: {+ const targetVar = (data as IfElseNodeType).conditions?.find(c => c.variable_selector.join('.') === valueSelector.join('.'))+ if (targetVar)+ res = `#${valueSelector.join('.')}#`+ break+ }+ case BlockEnum.Code: {+ const targetVar = (data as CodeNodeType).variables?.find(v => v.value_selector.join('.') === valueSelector.join('.'))+ if (targetVar)+ res = targetVar.variable+ break+ }+ case BlockEnum.TemplateTransform: {+ const targetVar = (data as TemplateTransformNodeType).variables?.find(v => v.value_selector.join('.') === valueSelector.join('.'))+ if (targetVar)+ res = targetVar.variable+ break+ }+ case BlockEnum.QuestionClassifier: {+ res = 'query'+ break+ }+ case BlockEnum.HttpRequest: {+ res = `#${valueSelector.join('.')}#`+ break+ }++ case BlockEnum.Tool: {+ res = `#${valueSelector.join('.')}#`+ break+ }++ case BlockEnum.VariableAssigner: {+ res = `#${valueSelector.join('.')}#`+ break+ }++ case BlockEnum.VariableAggregator: {+ res = `#${valueSelector.join('.')}#`+ break+ }++ case BlockEnum.ParameterExtractor: {+ res = 'query'+ break+ }+ }+ return res+}+export const findUsedVarNodes = (varSelector: ValueSelector, availableNodes: Node[]): Node[] => {const res: Node[] = []availableNodes.forEach((node) => {@@ -345,6 +634,7 @@ export const updateNodeVars = (oldNode: Node, oldVarSelector: ValueSelector, newconst newNode = produce(oldNode, (draft: any) => {const { data } = draftconst { type } = data+switch (type) {case BlockEnum.End: {const payload = data as EndNodeType@@ -480,6 +770,31 @@ export const updateNodeVars = (oldNode: Node, oldVarSelector: ValueSelector, new}break}+ case BlockEnum.VariableAggregator: {+ const payload = data as VariableAssignerNodeType+ if (payload.variables) {+ payload.variables = payload.variables.map((v) => {+ if (v.join('.') === oldVarSelector.join('.'))+ v = newVarSelector+ return v+ })+ }+ break+ }+ case BlockEnum.ParameterExtractor: {+ const payload = data as ParameterExtractorNodeType+ if (payload.query.join('.') === oldVarSelector.join('.'))+ payload.query = newVarSelector+ payload.instruction = replaceOldVarInText(payload.instruction, oldVarSelector, newVarSelector)+ break+ }+ case BlockEnum.Iteration: {+ const payload = data as IterationNodeType+ if (payload.iterator_selector.join('.') === oldVarSelector.join('.'))+ payload.iterator_selector = newVarSelector++ break+ }}})return newNode@@ -567,10 +882,33 @@ export const getNodeOutputVars = (node: Node, isChatMode: boolean): ValueSelectobreak}+ case BlockEnum.VariableAggregator: {+ res.push([id, 'output'])+ break+ }+case BlockEnum.Tool: {varsToValueSelectorList(TOOL_OUTPUT_STRUCT, [id], res)break}++ case BlockEnum.ParameterExtractor: {+ const {+ parameters,+ } = data as ParameterExtractorNodeType+ if (parameters?.length > 0) {+ parameters.forEach((p) => {+ res.push([id, p.name])+ })+ }++ break+ }++ case BlockEnum.Iteration: {+ res.push([id, 'output'])+ break+ }}return resdiff --git a/web/app/components/workflow/nodes/_base/components/variable/var-reference-picker.tsx b/web/app/components/workflow/nodes/_base/components/variable/var-reference-picker.tsxindex ec0926907a4..0032fbfd5bf 100644--- a/web/app/components/workflow/nodes/_base/components/variable/var-reference-picker.tsx+++ b/web/app/components/workflow/nodes/_base/components/variable/var-reference-picker.tsx@@ -4,10 +4,11 @@ import React, { useCallback, useEffect, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'import cn from 'classnames'import produce from 'immer'+import { useStoreApi } from 'reactflow'import VarReferencePopup from './var-reference-popup'-import { getNodeInfoById, isSystemVar, toNodeOutputVars } from './utils'-import type { ValueSelector, Var } from '@/app/components/workflow/types'-import { BlockEnum, VarType } from '@/app/components/workflow/types'+import { getNodeInfoById, getVarType, isSystemVar, toNodeAvailableVars } from './utils'+import type { Node, NodeOutPutVar, ValueSelector, Var } from '@/app/components/workflow/types'+import { BlockEnum } from '@/app/components/workflow/types'import { VarBlockIcon } from '@/app/components/workflow/block-icon'import { Line3 } from '@/app/components/base/icons/src/public/common'import { Variable02 } from '@/app/components/base/icons/src/vender/solid/development'@@ -24,7 +25,7 @@ import { VarType as VarKindType } from '@/app/components/workflow/nodes/tool/typimport TypeSelector from '@/app/components/workflow/nodes/_base/components/selector'import { ChevronDown } from '@/app/components/base/icons/src/vender/line/arrows'import { XClose } from '@/app/components/base/icons/src/vender/line/general'-+import AddButton from '@/app/components/base/button/add-button'const TRIGGER_DEFAULT_WIDTH = 227type Props = {@@ -33,12 +34,15 @@ type Props = {isShowNodeName: booleanreadonly: booleanvalue: ValueSelector | string- onChange: (value: ValueSelector | string, varKindType: VarKindType) => void+ onChange: (value: ValueSelector | string, varKindType: VarKindType, varInfo?: Var) => voidonOpen?: () => voidisSupportConstantValue?: booleandefaultVarKindType?: VarKindTypeonlyLeafNodeVar?: booleanfilterVar?: (payload: Var, valueSelector: ValueSelector) => boolean+ availableNodes?: Node[]+ availableVars?: NodeOutPutVar[]+ isAddBtnTrigger?: boolean}const VarReferencePicker: FC<Props> = ({@@ -53,8 +57,27 @@ const VarReferencePicker: FC<Props> = ({defaultVarKindType = VarKindType.constant,onlyLeafNodeVar,filterVar = () => true,+ availableNodes: passedInAvailableNodes,+ availableVars,+ isAddBtnTrigger,}) => {const { t } = useTranslation()+ const store = useStoreApi()+ const {+ getNodes,+ } = store.getState()+ const isChatMode = useIsChatMode()++ const { getTreeLeafNodes, getBeforeNodesInSameBranch } = useWorkflow()+ const availableNodes = passedInAvailableNodes || (onlyLeafNodeVar ? getTreeLeafNodes(nodeId) : getBeforeNodesInSameBranch(nodeId))+ const startNode = availableNodes.find((node: any) => {+ return node.data.type === BlockEnum.Start+ })++ const node = getNodes().find(n => n.id === nodeId)+ const isInIteration = !!node?.data.isInIteration+ const iterationNode = isInIteration ? getNodes().find(n => n.id === node.parentId) : null+const triggerRef = useRef<HTMLDivElement>(null)const [triggerWidth, setTriggerWidth] = useState(TRIGGER_DEFAULT_WIDTH)useEffect(() => {@@ -63,63 +86,60 @@ const VarReferencePicker: FC<Props> = ({// eslint-disable-next-line react-hooks/exhaustive-deps}, [triggerRef.current])- const isChatMode = useIsChatMode()const [varKindType, setVarKindType] = useState<VarKindType>(defaultVarKindType)const isConstant = isSupportConstantValue && varKindType === VarKindType.constant- const { getTreeLeafNodes, getBeforeNodesInSameBranch } = useWorkflow()- const availableNodes = onlyLeafNodeVar ? getTreeLeafNodes(nodeId) : getBeforeNodesInSameBranch(nodeId)- const allOutputVars = toNodeOutputVars(availableNodes, isChatMode)- const outputVars = toNodeOutputVars(availableNodes, isChatMode, filterVar)++ const outputVars = (() => {+ if (availableVars)+ return availableVars++ const vars = toNodeAvailableVars({+ parentNode: iterationNode,+ t,+ beforeNodes: availableNodes,+ isChatMode,+ filterVar,+ })++ return vars+ })()const [open, setOpen] = useState(false)useEffect(() => {onOpen()// eslint-disable-next-line react-hooks/exhaustive-deps}, [open])const hasValue = !isConstant && value.length > 0- const startNode = availableNodes.find((node: any) => {- return node.data.type === BlockEnum.Start- })++ const isIterationVar = (() => {+ if (!isInIteration)+ return false+ if (value[0] === node?.parentId && ['item', 'index'].includes(value[1]))+ return true+ return false+ })()+const outputVarNodeId = hasValue ? value[0] : ''const outputVarNode = (() => {if (!hasValue || isConstant)return null++ if (isIterationVar)+ return iterationNode?.data+if (isSystemVar(value as ValueSelector))return startNode?.datareturn getNodeInfoById(availableNodes, outputVarNodeId)?.data})()- const varName = hasValue ? `${isSystemVar(value as ValueSelector) ? 'sys.' : ''}${value[value.length - 1]}` : ''-- const getVarType = () => {- if (isConstant)- return 'undefined'- const isSystem = isSystemVar(value as ValueSelector)- const targetVarNodeId = isSystem ? startNode?.id : outputVarNodeId- const targetVar = allOutputVars.find(v => v.nodeId === targetVarNodeId)-- if (!targetVar)- return 'undefined'- let type: VarType = VarType.string- let curr: any = targetVar.vars- if (isSystem) {- return curr.find((v: any) => v.variable === (value as ValueSelector).join('.'))?.type+ const varName = (() => {+ if (hasValue) {+ const isSystem = isSystemVar(value as ValueSelector)+ const varName = value.length >= 3 ? (value as ValueSelector).slice(-2).join('.') : value[value.length - 1]+ return `${isSystem ? 'sys.' : ''}${varName}`}- else {- (value as ValueSelector).slice(1).forEach((key, i) => {- const isLast = i === value.length - 2- curr = curr.find((v: any) => v.variable === key)- if (isLast) {- type = curr?.type- }- else {- if (curr.type === VarType.object)- curr = curr.children- }- })- return type- }- }+ return ''+ })()const varKindTypes = [{@@ -150,7 +170,7 @@ const VarReferencePicker: FC<Props> = ({}}, [controlFocus])- const handleVarReferenceChange = useCallback((value: ValueSelector) => {+ const handleVarReferenceChange = useCallback((value: ValueSelector, varInfo: Var) => {// sys var not passed to backendconst newValue = produce(value, (draft) => {if (draft[1] && draft[1].startsWith('sys')) {@@ -161,7 +181,7 @@ const VarReferencePicker: FC<Props> = ({})}})- onChange(newValue, varKindType)+ onChange(newValue, varKindType, varInfo)setOpen(false)}, [onChange, varKindType])@@ -176,7 +196,14 @@ const VarReferencePicker: FC<Props> = ({onChange([], varKindType)}, [onChange, varKindType])- const type = getVarType()+ const type = getVarType({+ parentNode: iterationNode,+ valueSelector: value as ValueSelector,+ availableNodes,+ isChatMode,+ isConstant: !!isConstant,+ })+// 8(left/right-padding) + 14(icon) + 4 + 14 + 2 = 42 + 17 buffconst availableWidth = triggerWidth - 56const [maxNodeNameWidth, maxVarNameWidth, maxTypeWidth] = (() => {@@ -193,86 +220,92 @@ const VarReferencePicker: FC<Props> = ({<PortalToFollowElemopen={open}onOpenChange={setOpen}- placement='bottom-start'+ placement={isAddBtnTrigger ? 'bottom-end' : 'bottom-start'}><PortalToFollowElemTrigger onClick={() => {if (readonly)return!isConstant ? setOpen(!open) : setControlFocus(Date.now())}} className='!flex'>- <div ref={triggerRef} className={cn((open || isFocus) ? 'border-gray-300' : 'border-gray-100', 'relative group/wrap flex items-center w-full h-8 p-1 rounded-lg bg-gray-100 border')}>- {isSupportConstantValue- ? <div onClick={(e) => {- e.stopPropagation()- setOpen(false)- setControlFocus(Date.now())- }} className='mr-1 flex items-center space-x-1'>- <TypeSelector- noLeft- triggerClassName='!text-xs'- readonly={readonly}- DropDownIcon={ChevronDown}- value={varKindType}- options={varKindTypes}- onChange={handleVarKindTypeChange}- />- <div className='h-4 w-px bg-black/5'></div>+ {isAddBtnTrigger+ ? (+ <div>+ <AddButton onClick={() => { }}></AddButton></div>- : (!hasValue && <div className='ml-1.5 mr-1'>- <Variable02 className='w-3.5 h-3.5 text-gray-400' />- </div>)}- {isConstant- ? (- <input- type='text'- className='w-full h-8 leading-8 pl-0.5 bg-transparent text-[13px] font-normal text-gray-900 placeholder:text-gray-400 focus:outline-none overflow-hidden'- value={isConstant ? value : ''}- onChange={handleStaticChange}- onFocus={() => setIsFocus(true)}- onBlur={() => setIsFocus(false)}- readOnly={readonly}- />- )- : (- <div className={cn('inline-flex h-full items-center px-1.5 rounded-[5px]', hasValue && 'bg-white')}>- {hasValue- ? (- <>- {isShowNodeName && (- <div className='flex items-center'>- <div className='p-[1px]'>- <VarBlockIcon- className='!text-gray-900'- type={outputVarNode?.type || BlockEnum.Start}- />+ )+ : (<div ref={triggerRef} className={cn((open || isFocus) ? 'border-gray-300' : 'border-gray-100', 'relative group/wrap flex items-center w-full h-8 p-1 rounded-lg bg-gray-100 border')}>+ {isSupportConstantValue+ ? <div onClick={(e) => {+ e.stopPropagation()+ setOpen(false)+ setControlFocus(Date.now())+ }} className='mr-1 flex items-center space-x-1'>+ <TypeSelector+ noLeft+ triggerClassName='!text-xs'+ readonly={readonly}+ DropDownIcon={ChevronDown}+ value={varKindType}+ options={varKindTypes}+ onChange={handleVarKindTypeChange}+ />+ <div className='h-4 w-px bg-black/5'></div>+ </div>+ : (!hasValue && <div className='ml-1.5 mr-1'>+ <Variable02 className='w-3.5 h-3.5 text-gray-400' />+ </div>)}+ {isConstant+ ? (+ <input+ type='text'+ className='w-full h-8 leading-8 pl-0.5 bg-transparent text-[13px] font-normal text-gray-900 placeholder:text-gray-400 focus:outline-none overflow-hidden'+ value={isConstant ? value : ''}+ onChange={handleStaticChange}+ onFocus={() => setIsFocus(true)}+ onBlur={() => setIsFocus(false)}+ readOnly={readonly}+ />+ )+ : (+ <div className={cn('inline-flex h-full items-center px-1.5 rounded-[5px]', hasValue && 'bg-white')}>+ {hasValue+ ? (+ <>+ {isShowNodeName && (+ <div className='flex items-center'>+ <div className='p-[1px]'>+ <VarBlockIcon+ className='!text-gray-900'+ type={outputVarNode?.type || BlockEnum.Start}+ />+ </div>+ <div className='mx-0.5 text-xs font-medium text-gray-700 truncate' title={outputVarNode?.title} style={{+ maxWidth: maxNodeNameWidth,+ }}>{outputVarNode?.title}</div>+ <Line3 className='mr-0.5'></Line3></div>- <div className='mx-0.5 text-xs font-medium text-gray-700 truncate' title={outputVarNode?.title} style={{- maxWidth: maxNodeNameWidth,- }}>{outputVarNode?.title}</div>- <Line3 className='mr-0.5'></Line3>+ )}+ <div className='flex items-center text-primary-600'>+ {!hasValue && <Variable02 className='w-3.5 h-3.5' />}+ <div className='ml-0.5 text-xs font-medium truncate' title={varName} style={{+ maxWidth: maxVarNameWidth,+ }}>{varName}</div></div>- )}- <div className='flex items-center text-primary-600'>- {!hasValue && <Variable02 className='w-3.5 h-3.5' />}- <div className='ml-0.5 text-xs font-medium truncate' title={varName} style={{- maxWidth: maxVarNameWidth,- }}>{varName}</div>- </div>- <div className='ml-0.5 text-xs font-normal text-gray-500 capitalize truncate' title={type} style={{- maxWidth: maxTypeWidth,- }}>{type}</div>- </>- )- : <div className='text-[13px] font-normal text-gray-400'>{t('workflow.common.setVarValuePlaceholder')}</div>}- </div>- )}- {(hasValue && !readonly) && (<div- className='invisible group-hover/wrap:visible absolute h-5 right-1 top-[50%] translate-y-[-50%] group p-1 rounded-md hover:bg-black/5 cursor-pointer'- onClick={handleClearVar}- >- <XClose className='w-3.5 h-3.5 text-gray-500 group-hover:text-gray-800' />+ <div className='ml-0.5 text-xs font-normal text-gray-500 capitalize truncate' title={type} style={{+ maxWidth: maxTypeWidth,+ }}>{type}</div>+ </>+ )+ : <div className='text-[13px] font-normal text-gray-400'>{t('workflow.common.setVarValuePlaceholder')}</div>}+ </div>+ )}+ {(hasValue && !readonly) && (<div+ className='invisible group-hover/wrap:visible absolute h-5 right-1 top-[50%] translate-y-[-50%] group p-1 rounded-md hover:bg-black/5 cursor-pointer'+ onClick={handleClearVar}+ >+ <XClose className='w-3.5 h-3.5 text-gray-500 group-hover:text-gray-800' />+ </div>)}</div>)}- </div></PortalToFollowElemTrigger><PortalToFollowElemContent style={{zIndex: 100,@@ -281,7 +314,7 @@ const VarReferencePicker: FC<Props> = ({<VarReferencePopupvars={outputVars}onChange={handleVarReferenceChange}- itemWidth={triggerWidth}+ itemWidth={isAddBtnTrigger ? 260 : triggerWidth}/>)}</PortalToFollowElemContent>diff --git a/web/app/components/workflow/nodes/_base/components/variable/var-reference-popup.tsx b/web/app/components/workflow/nodes/_base/components/variable/var-reference-popup.tsxindex 7e94099d6c8..114d849d50c 100644--- a/web/app/components/workflow/nodes/_base/components/variable/var-reference-popup.tsx+++ b/web/app/components/workflow/nodes/_base/components/variable/var-reference-popup.tsx@@ -2,11 +2,11 @@import type { FC } from 'react'import React from 'react'import VarReferenceVars from './var-reference-vars'-import { type NodeOutPutVar, type ValueSelector } from '@/app/components/workflow/types'+import type { NodeOutPutVar, ValueSelector, Var } from '@/app/components/workflow/types'type Props = {vars: NodeOutPutVar[]- onChange: (value: ValueSelector) => void+ onChange: (value: ValueSelector, varDetail: Var) => voiditemWidth?: number}const VarReferencePopup: FC<Props> = ({diff --git a/web/app/components/workflow/nodes/_base/hooks/use-available-var-list.ts b/web/app/components/workflow/nodes/_base/hooks/use-available-var-list.tsindex 066e5480365..3d5937048fc 100644--- a/web/app/components/workflow/nodes/_base/hooks/use-available-var-list.ts+++ b/web/app/components/workflow/nodes/_base/hooks/use-available-var-list.ts@@ -1,14 +1,16 @@+import { useTranslation } from 'react-i18next'+import useNodeInfo from './use-node-info'import {useIsChatMode,useWorkflow,} from '@/app/components/workflow/hooks'-import { toNodeOutputVars } from '@/app/components/workflow/nodes/_base/components/variable/utils'+import { toNodeAvailableVars } from '@/app/components/workflow/nodes/_base/components/variable/utils'import type { ValueSelector, Var } from '@/app/components/workflow/types'-type Params = {onlyLeafNodeVar?: booleanfilterVar: (payload: Var, selector: ValueSelector) => boolean}+const useAvailableVarList = (nodeId: string, {onlyLeafNodeVar,filterVar,@@ -16,14 +18,29 @@ const useAvailableVarList = (nodeId: string, {onlyLeafNodeVar: false,filterVar: () => true,}) => {+ const { t } = useTranslation()+const { getTreeLeafNodes, getBeforeNodesInSameBranch } = useWorkflow()const isChatMode = useIsChatMode()const availableNodes = onlyLeafNodeVar ? getTreeLeafNodes(nodeId) : getBeforeNodesInSameBranch(nodeId)- const availableVars = toNodeOutputVars(availableNodes, isChatMode, filterVar)++ const {+ parentNode: iterationNode,+ } = useNodeInfo(nodeId)++ const availableVars = toNodeAvailableVars({+ parentNode: iterationNode,+ t,+ beforeNodes: availableNodes,+ isChatMode,+ filterVar,+ })+return {availableVars,availableNodes,+ availableNodesWithParent: iterationNode ? [...availableNodes, iterationNode] : availableNodes,}}diff --git a/web/app/components/workflow/nodes/_base/hooks/use-node-info.ts b/web/app/components/workflow/nodes/_base/hooks/use-node-info.tsnew file mode 100644index 00000000000..f8f076dfdf0--- /dev/null+++ b/web/app/components/workflow/nodes/_base/hooks/use-node-info.ts@@ -0,0 +1,20 @@+import { useStoreApi } from 'reactflow'++const useNodeInfo = (nodeId: string) => {+ const store = useStoreApi()+ const {+ getNodes,+ } = store.getState()+ const allNodes = getNodes()+ const node = allNodes.find(n => n.id === nodeId)+ const isInIteration = !!node?.data.isInIteration+ const parentNodeId = node?.parentId+ const parentNode = allNodes.find(n => n.id === parentNodeId)+ return {+ node,+ isInIteration,+ parentNode,+ }+}++export default useNodeInfodiff --git a/web/app/components/workflow/nodes/_base/hooks/use-one-step-run.ts b/web/app/components/workflow/nodes/_base/hooks/use-one-step-run.tsindex 4a07e5a8768..ec2ce217b11 100644--- a/web/app/components/workflow/nodes/_base/hooks/use-one-step-run.ts+++ b/web/app/components/workflow/nodes/_base/hooks/use-one-step-run.ts@@ -1,6 +1,7 @@import { useEffect, useState } from 'react'import { useTranslation } from 'react-i18next'import { unionBy } from 'lodash-es'+import produce from 'immer'import {useIsChatMode,useNodeDataUpdate,@@ -11,7 +12,7 @@ import { getNodeInfoById, isSystemVar, toNodeOutputVars } from '@/app/componentsimport type { CommonNodeType, InputVar, ValueSelector, Var, Variable } from '@/app/components/workflow/types'import { BlockEnum, InputVarType, NodeRunningStatus, VarType } from '@/app/components/workflow/types'import { useStore as useAppStore } from '@/app/components/app/store'-import { singleNodeRun } from '@/service/workflow'+import { getIterationSingleNodeRunUrl, singleNodeRun } from '@/service/workflow'import Toast from '@/app/components/base/toast'import LLMDefault from '@/app/components/workflow/nodes/llm/default'import KnowledgeRetrievalDefault from '@/app/components/workflow/nodes/knowledge-retrieval/default'@@ -22,7 +23,12 @@ import QuestionClassifyDefault from '@/app/components/workflow/nodes/question-climport HTTPDefault from '@/app/components/workflow/nodes/http/default'import ToolDefault from '@/app/components/workflow/nodes/tool/default'import VariableAssigner from '@/app/components/workflow/nodes/variable-assigner/default'+import ParameterExtractorDefault from '@/app/components/workflow/nodes/parameter-extractor/default'+import IterationDefault from '@/app/components/workflow/nodes/iteration/default'+import { ssePost } from '@/service/base'+import { getInputVars as doGetInputVars } from '@/app/components/base/prompt-editor/constants'+import type { NodeTracing } from '@/types/workflow'const { checkValid: checkLLMValid } = LLMDefaultconst { checkValid: checkKnowledgeRetrievalValid } = KnowledgeRetrievalDefaultconst { checkValid: checkIfElseValid } = IfElseDefault@@ -32,6 +38,8 @@ const { checkValid: checkQuestionClassifyValid } = QuestionClassifyDefaultconst { checkValid: checkHttpValid } = HTTPDefaultconst { checkValid: checkToolValid } = ToolDefaultconst { checkValid: checkVariableAssignerValid } = VariableAssigner+const { checkValid: checkParameterExtractorValid } = ParameterExtractorDefault+const { checkValid: checkIterationValid } = IterationDefaultconst checkValidFns: Record<BlockEnum, Function> = {[BlockEnum.LLM]: checkLLMValid,@@ -43,6 +51,9 @@ const checkValidFns: Record<BlockEnum, Function> = {[BlockEnum.HttpRequest]: checkHttpValid,[BlockEnum.Tool]: checkToolValid,[BlockEnum.VariableAssigner]: checkVariableAssignerValid,+ [BlockEnum.VariableAggregator]: checkVariableAssignerValid,+ [BlockEnum.ParameterExtractor]: checkParameterExtractorValid,+ [BlockEnum.Iteration]: checkIterationValid,} as anytype Params<T> = {@@ -50,6 +61,7 @@ type Params<T> = {data: CommonNodeType<T>defaultRunInputData: Record<string, any>moreDataForCheckValid?: any+ iteratorInputKey?: string}const varTypeToInputVarType = (type: VarType, {@@ -78,13 +90,16 @@ const useOneStepRun = <T>({data,defaultRunInputData,moreDataForCheckValid,+ iteratorInputKey,}: Params<T>) => {const { t } = useTranslation()- const { getBeforeNodesInSameBranch } = useWorkflow() as any+ const { getBeforeNodesInSameBranch, getBeforeNodesInSameBranchIncludeParent } = useWorkflow() as anyconst isChatMode = useIsChatMode()+ const isIteration = data.type === BlockEnum.Iterationconst availableNodes = getBeforeNodesInSameBranch(id)- const allOutputVars = toNodeOutputVars(getBeforeNodesInSameBranch(id), isChatMode)+ const availableNodesIncludeParent = getBeforeNodesInSameBranchIncludeParent(id)+ const allOutputVars = toNodeOutputVars(availableNodes, isChatMode)const getVar = (valueSelector: ValueSelector): Var | undefined => {let res: Var | undefinedconst isSystem = valueSelector[0] === 'sys'@@ -95,14 +110,17 @@ const useOneStepRun = <T>({return targetVar.vars.find(item => item.variable.split('.')[1] === valueSelector[1])let curr: any = targetVar.vars+ if (!curr)+ return+valueSelector.slice(1).forEach((key, i) => {const isLast = i === valueSelector.length - 2- curr = curr.find((v: any) => v.variable === key)+ curr = curr?.find((v: any) => v.variable === key)if (isLast) {res = curr}else {- if (curr.type === VarType.object)+ if (curr?.type === VarType.object)curr = curr.children}})@@ -113,11 +131,14 @@ const useOneStepRun = <T>({const checkValid = checkValidFns[data.type]const appId = useAppStore.getState().appDetail?.idconst [runInputData, setRunInputData] = useState<Record<string, any>>(defaultRunInputData || {})+ const iterationTimes = iteratorInputKey ? runInputData[iteratorInputKey].length : 0const [runResult, setRunResult] = useState<any>(null)const { handleNodeDataUpdate }: { handleNodeDataUpdate: (data: any) => void } = useNodeDataUpdate()const [canShowSingleRun, setCanShowSingleRun] = useState(false)const isShowSingleRun = data._isSingleRun && canShowSingleRun+ const [iterationRunResult, setIterationRunResult] = useState<NodeTracing[][]>([])+useEffect(() => {if (!checkValid) {setCanShowSingleRun(true)@@ -152,6 +173,15 @@ const useOneStepRun = <T>({},})}+ const showSingleRun = () => {+ handleNodeDataUpdate({+ id,+ data: {+ ...data,+ _isSingleRun: true,+ },+ })+ }const runningStatus = data._singleRunningStatus || NodeRunningStatus.NotStartconst isCompleted = runningStatus === NodeRunningStatus.Succeeded || runningStatus === NodeRunningStatus.Failed@@ -165,34 +195,117 @@ const useOneStepRun = <T>({})let res: anytry {- res = await singleNodeRun(appId!, id, { inputs: submitData }) as any+ if (!isIteration) {+ res = await singleNodeRun(appId!, id, { inputs: submitData }) as any+ }+ else {+ setIterationRunResult([])+ let _iterationResult: NodeTracing[][] = []+ let _runResult: any = null+ ssePost(+ getIterationSingleNodeRunUrl(isChatMode, appId!, id),+ { body: { inputs: submitData } },+ {+ onWorkflowStarted: () => {+ },+ onWorkflowFinished: (params) => {+ handleNodeDataUpdate({+ id,+ data: {+ ...data,+ _singleRunningStatus: NodeRunningStatus.Succeeded,+ },+ })+ const { data: iterationData } = params+ _runResult.created_by = iterationData.created_by.name+ setRunResult(_runResult)+ },+ onIterationNext: () => {+ // iteration next trigger time is triggered one more time than iterationTimes+ if (_iterationResult.length >= iterationTimes!)+ return++ const newIterationRunResult = produce(_iterationResult, (draft) => {+ draft.push([])+ })+ _iterationResult = newIterationRunResult+ setIterationRunResult(newIterationRunResult)+ },+ onIterationFinish: (params) => {+ _runResult = params.data+ setRunResult(_runResult)+ },+ onNodeStarted: (params) => {+ const newIterationRunResult = produce(_iterationResult, (draft) => {+ draft[draft.length - 1].push({+ ...params.data,+ status: NodeRunningStatus.Running,+ } as NodeTracing)+ })+ _iterationResult = newIterationRunResult+ setIterationRunResult(newIterationRunResult)+ },+ onNodeFinished: (params) => {+ const iterationRunResult = _iterationResult++ const { data } = params+ const currentIndex = iterationRunResult[iterationRunResult.length - 1].findIndex(trace => trace.node_id === data.node_id)+ const newIterationRunResult = produce(iterationRunResult, (draft) => {+ if (currentIndex > -1) {+ draft[draft.length - 1][currentIndex] = {+ ...data,+ status: NodeRunningStatus.Succeeded,+ } as NodeTracing+ }+ })+ _iterationResult = newIterationRunResult+ setIterationRunResult(newIterationRunResult)+ },+ onError: () => {+ handleNodeDataUpdate({+ id,+ data: {+ ...data,+ _singleRunningStatus: NodeRunningStatus.Failed,+ },+ })+ },+ },+ )+ }if (res.error)throw new Error(res.error)}catch (e: any) {+ if (!isIteration) {+ handleNodeDataUpdate({+ id,+ data: {+ ...data,+ _singleRunningStatus: NodeRunningStatus.Failed,+ },+ })+ return false+ }+ }+ finally {+ if (!isIteration) {+ setRunResult({+ ...res,+ total_tokens: res.execution_metadata?.total_tokens || 0,+ created_by: res.created_by_account?.name || '',+ })+ }+ }+ if (!isIteration) {handleNodeDataUpdate({id,data: {...data,- _singleRunningStatus: NodeRunningStatus.Failed,+ _singleRunningStatus: NodeRunningStatus.Succeeded,},})- return false}- finally {- setRunResult({- ...res,- total_tokens: res.execution_metadata?.total_tokens || 0,- created_by: res.created_by_account?.name || '',- })- }- handleNodeDataUpdate({- id,- data: {- ...data,- _singleRunningStatus: NodeRunningStatus.Succeeded,- },- })}const handleStop = () => {@@ -241,12 +354,12 @@ const useOneStepRun = <T>({})const variables = unionBy(valueSelectors, item => item.join('.')).map((item) => {- const varInfo = getNodeInfoById(availableNodes, item[0])?.data+ const varInfo = getNodeInfoById(availableNodesIncludeParent, item[0])?.datareturn {label: {nodeType: varInfo?.type,- nodeName: varInfo?.title || availableNodes[0]?.data.title, // default start node title+ nodeName: varInfo?.title || availableNodesIncludeParent[0]?.data.title, // default start node titlevariable: isSystemVar(item) ? item.join('.') : item[item.length - 1],},variable: `#${item.join('.')}#`,@@ -261,6 +374,7 @@ const useOneStepRun = <T>({return {isShowSingleRun,hideSingleRun,+ showSingleRun,toVarInputs,getInputVars,runningStatus,@@ -270,6 +384,7 @@ const useOneStepRun = <T>({runInputData,setRunInputData,runResult,+ iterationRunResult,}}diff --git a/web/app/components/workflow/nodes/_base/node.tsx b/web/app/components/workflow/nodes/_base/node.tsxindex c5fcd5b99db..2b614f936ad 100644--- a/web/app/components/workflow/nodes/_base/node.tsx+++ b/web/app/components/workflow/nodes/_base/node.tsx@@ -5,9 +5,11 @@ import type {import {cloneElement,memo,+ useEffect,useMemo,useRef,} from 'react'+import cn from 'classnames'import type { NodeProps } from '../../types'import {BlockEnum,@@ -17,11 +19,14 @@ import {useNodesReadOnly,useToolIcon,} from '../../hooks'+import { useNodeIterationInteractions } from '../iteration/use-interactions'import {NodeSourceHandle,NodeTargetHandle,} from './components/node-handle'+import NodeResizer from './components/node-resizer'import NodeControl from './components/node-control'+import AddVariablePopupWithPosition from './components/add-variable-popup-with-position'import BlockIcon from '@/app/components/workflow/block-icon'import {CheckCircle,@@ -40,9 +45,24 @@ const BaseNode: FC<BaseNodeProps> = ({}) => {const nodeRef = useRef<HTMLDivElement>(null)const { nodesReadOnly } = useNodesReadOnly()+ const { handleNodeIterationChildSizeChange } = useNodeIterationInteractions()const toolIcon = useToolIcon(data)- const showSelectedBorder = data.selected || data._isBundled+ useEffect(() => {+ if (nodeRef.current && data.selected && data.isInIteration) {+ const resizeObserver = new ResizeObserver(() => {+ handleNodeIterationChildSizeChange(id)+ })++ resizeObserver.observe(nodeRef.current)++ return () => {+ resizeObserver.disconnect()+ }+ }+ }, [data.isInIteration, data.selected, id, handleNodeIterationChildSizeChange])++ const showSelectedBorder = data.selected || data._isBundled || data._isEnteringconst {showRunningBorder,showSuccessBorder,@@ -57,26 +77,47 @@ const BaseNode: FC<BaseNodeProps> = ({return (<div- className={`- flex border-[2px] rounded-2xl- ${(showSelectedBorder && !data._isInvalidConnection) ? 'border-primary-600' : 'border-transparent'}- `}+ className={cn(+ 'flex border-[2px] rounded-2xl',+ showSelectedBorder ? 'border-primary-600' : 'border-transparent',+ )}ref={nodeRef}+ style={{+ width: data.type === BlockEnum.Iteration ? data.width : 'auto',+ height: data.type === BlockEnum.Iteration ? data.height : 'auto',+ }}><div- className={`- group relative pb-1 w-[240px] bg-[#fcfdff] shadow-xs- border border-transparent rounded-[15px]- ${!data._runningStatus && 'hover:shadow-lg'}- ${showRunningBorder && '!border-primary-500'}- ${showSuccessBorder && '!border-[#12B76A]'}- ${showFailedBorder && '!border-[#F04438]'}- ${data._isInvalidConnection && '!border-[#F04438]'}- ${data._isBundled && '!shadow-lg'}- `}+ className={cn(+ 'group relative pb-1 shadow-xs',+ 'border border-transparent rounded-[15px]',+ data.type !== BlockEnum.Iteration && 'w-[240px] bg-[#fcfdff]',+ data.type === BlockEnum.Iteration && 'flex flex-col w-full h-full bg-[#fcfdff]/80',+ !data._runningStatus && 'hover:shadow-lg',+ showRunningBorder && '!border-primary-500',+ showSuccessBorder && '!border-[#12B76A]',+ showFailedBorder && '!border-[#F04438]',+ data._isBundled && '!shadow-lg',+ )}>{- data.type !== BlockEnum.VariableAssigner && !data._isCandidate && (+ data._showAddVariablePopup && (+ <AddVariablePopupWithPosition+ nodeId={id}+ nodeData={data}+ />+ )+ }+ {+ data.type === BlockEnum.Iteration && (+ <NodeResizer+ nodeId={id}+ nodeData={data}+ />+ )+ }+ {+ data.type !== BlockEnum.VariableAssigner && data.type !== BlockEnum.VariableAggregator && !data._isCandidate && (<NodeTargetHandleid={id}data={data}@@ -103,7 +144,10 @@ const BaseNode: FC<BaseNodeProps> = ({/>)}- <div className='flex items-center px-3 pt-3 pb-2'>+ <div className={cn(+ 'flex items-center px-3 pt-3 pb-2 rounded-t-2xl',+ data.type === BlockEnum.Iteration && 'bg-[rgba(250,252,255,0.9)]',+ )}><BlockIconclassName='shrink-0 mr-2'type={data.type}@@ -116,6 +160,13 @@ const BaseNode: FC<BaseNodeProps> = ({>{data.title}</div>+ {+ data._iterationLength && data._iterationIndex && data._runningStatus === NodeRunningStatus.Running && (+ <div className='mr-1.5 text-xs font-medium text-primary-600'>+ {data._iterationIndex}/{data._iterationLength}+ </div>+ )+ }{(data._runningStatus === NodeRunningStatus.Running || data._singleRunningStatus === NodeRunningStatus.Running) && (<Loading02 className='w-3.5 h-3.5 text-primary-600 animate-spin' />@@ -132,9 +183,20 @@ const BaseNode: FC<BaseNodeProps> = ({)}</div>- {cloneElement(children, { id, data })}{- data.desc && (+ data.type !== BlockEnum.Iteration && (+ cloneElement(children, { id, data })+ )+ }+ {+ data.type === BlockEnum.Iteration && (+ <div className='grow pl-1 pr-1 pb-1'>+ {cloneElement(children, { id, data })}+ </div>+ )+ }+ {+ data.desc && data.type !== BlockEnum.Iteration && (<div className='px-3 pt-1 pb-2 text-xs leading-[18px] text-gray-500 whitespace-pre-line break-words'>{data.desc}</div>diff --git a/web/app/components/workflow/nodes/answer/panel.tsx b/web/app/components/workflow/nodes/answer/panel.tsxindex 460f61a363c..feb07c36c9a 100644--- a/web/app/components/workflow/nodes/answer/panel.tsx+++ b/web/app/components/workflow/nodes/answer/panel.tsx@@ -21,7 +21,7 @@ const Panel: FC<NodePanelProps<AnswerNodeType>> = ({filterVar,} = useConfig(id, data)- const { availableVars, availableNodes } = useAvailableVarList(id, {+ const { availableVars, availableNodesWithParent } = useAvailableVarList(id, {onlyLeafNodeVar: false,filterVar,})@@ -35,7 +35,7 @@ const Panel: FC<NodePanelProps<AnswerNodeType>> = ({value={inputs.answer}onChange={handleAnswerChange}nodesOutputVars={availableVars}- availableNodes={availableNodes}+ availableNodes={availableNodesWithParent}/></div>)diff --git a/web/app/components/workflow/nodes/constants.ts b/web/app/components/workflow/nodes/constants.tsindex 734093eb7b9..c67ce757ab2 100644--- a/web/app/components/workflow/nodes/constants.ts+++ b/web/app/components/workflow/nodes/constants.ts@@ -24,6 +24,10 @@ import ToolNode from './tool/node'import ToolPanel from './tool/panel'import VariableAssignerNode from './variable-assigner/node'import VariableAssignerPanel from './variable-assigner/panel'+import ParameterExtractorNode from './parameter-extractor/node'+import ParameterExtractorPanel from './parameter-extractor/panel'+import IterationNode from './iteration/node'+import IterationPanel from './iteration/panel'export const NodeComponentMap: Record<string, ComponentType<any>> = {[BlockEnum.Start]: StartNode,@@ -38,6 +42,9 @@ export const NodeComponentMap: Record<string, ComponentType<any>> = {[BlockEnum.HttpRequest]: HttpNode,[BlockEnum.Tool]: ToolNode,[BlockEnum.VariableAssigner]: VariableAssignerNode,+ [BlockEnum.VariableAggregator]: VariableAssignerNode,+ [BlockEnum.ParameterExtractor]: ParameterExtractorNode,+ [BlockEnum.Iteration]: IterationNode,}export const PanelComponentMap: Record<string, ComponentType<any>> = {@@ -53,4 +60,7 @@ export const PanelComponentMap: Record<string, ComponentType<any>> = {[BlockEnum.HttpRequest]: HttpPanel,[BlockEnum.Tool]: ToolPanel,[BlockEnum.VariableAssigner]: VariableAssignerPanel,+ [BlockEnum.VariableAggregator]: VariableAssignerPanel,+ [BlockEnum.ParameterExtractor]: ParameterExtractorPanel,+ [BlockEnum.Iteration]: IterationPanel,}diff --git a/web/app/components/workflow/nodes/end/node.tsx b/web/app/components/workflow/nodes/end/node.tsxindex e083171a552..af7e646bee0 100644--- a/web/app/components/workflow/nodes/end/node.tsx+++ b/web/app/components/workflow/nodes/end/node.tsx@@ -1,8 +1,8 @@import type { FC } from 'react'import React from 'react'import type { EndNodeType } from './types'-import type { NodeProps, ValueSelector, Variable } from '@/app/components/workflow/types'-import { isSystemVar, toNodeOutputVars } from '@/app/components/workflow/nodes/_base/components/variable/utils'+import type { NodeProps, Variable } from '@/app/components/workflow/types'+import { getVarType, isSystemVar } from '@/app/components/workflow/nodes/_base/components/variable/utils'import {useIsChatMode,useWorkflow,@@ -10,7 +10,7 @@ import {import { VarBlockIcon } from '@/app/components/workflow/block-icon'import { Line3 } from '@/app/components/base/icons/src/public/common'import { Variable02 } from '@/app/components/base/icons/src/vender/solid/development'-import { BlockEnum, VarType } from '@/app/components/workflow/types'+import { BlockEnum } from '@/app/components/workflow/types'const Node: FC<NodeProps<EndNodeType>> = ({id,@@ -19,7 +19,6 @@ const Node: FC<NodeProps<EndNodeType>> = ({const { getBeforeNodesInSameBranch } = useWorkflow()const availableNodes = getBeforeNodesInSameBranch(id)const isChatMode = useIsChatMode()- const outputVars = toNodeOutputVars(availableNodes, isChatMode)const startNode = availableNodes.find((node: any) => {return node.data.type === BlockEnum.Start@@ -29,27 +28,6 @@ const Node: FC<NodeProps<EndNodeType>> = ({return availableNodes.find(node => node.id === id) || startNode}- const getVarType = (nodeId: string, value: ValueSelector) => {- const targetVar = outputVars.find(v => v.nodeId === nodeId)- if (!targetVar)- return 'undefined'-- let type: VarType = VarType.string- let curr: any = targetVar.vars- const isSystem = isSystemVar(value);- (value).slice(1).forEach((key, i) => {- const isLast = i === value.length - 2- curr = curr.find((v: any) => v.variable === isSystem ? `sys.${key}` : key)- if (isLast) {- type = curr.type- }- else {- if (curr.type === VarType.object)- curr = curr.children- }- })- return type- }const { outputs } = dataconst filteredOutputs = (outputs as Variable[]).filter(({ value_selector }) => value_selector.length > 0)@@ -62,6 +40,11 @@ const Node: FC<NodeProps<EndNodeType>> = ({const node = getNode(value_selector[0])const isSystem = isSystemVar(value_selector)const varName = isSystem ? `sys.${value_selector[value_selector.length - 1]}` : value_selector[value_selector.length - 1]+ const varType = getVarType({+ valueSelector: value_selector,+ availableNodes,+ isChatMode,+ })return (<div key={index} className='flex items-center h-6 justify-between bg-gray-100 rounded-md px-1 space-x-1 text-xs font-normal text-gray-700'><div className='flex items-center text-xs font-medium text-gray-500'>@@ -79,7 +62,7 @@ const Node: FC<NodeProps<EndNodeType>> = ({</div></div><div className='text-xs font-normal text-gray-700'>- <div className='max-w-[42px] ml-0.5 text-xs font-normal text-gray-500 capitalize truncate' title={getVarType(node?.id || '', value_selector)}>{getVarType(node?.id || '', value_selector)}</div>+ <div className='max-w-[42px] ml-0.5 text-xs font-normal text-gray-500 capitalize truncate' title={varType}>{varType}</div></div></div>)diff --git a/web/app/components/workflow/nodes/if-else/components/condition-item.tsx b/web/app/components/workflow/nodes/if-else/components/condition-item.tsxindex 4a9635984d4..4e1163c860a 100644--- a/web/app/components/workflow/nodes/if-else/components/condition-item.tsx+++ b/web/app/components/workflow/nodes/if-else/components/condition-item.tsx@@ -96,7 +96,7 @@ const Item: FC<ItemProps> = ({readonly,nodeId,payload,- varType,+ varType = VarType.string,onChange,canRemove,onRemove = () => { },@@ -184,7 +184,7 @@ const Item: FC<ItemProps> = ({e.stopPropagation()return}- if (!varType) {+ if (!payload.variable_selector || payload.variable_selector.length === 0) {e.stopPropagation()Toast.notify({message: t(`${i18nPrefix}.notSetVariable`),diff --git a/web/app/components/workflow/nodes/if-else/default.ts b/web/app/components/workflow/nodes/if-else/default.tsindex 65f850c76c8..befd2de2e1e 100644--- a/web/app/components/workflow/nodes/if-else/default.ts+++ b/web/app/components/workflow/nodes/if-else/default.ts@@ -27,7 +27,7 @@ const nodeDefault: NodeDefault<IfElseNodeType> = {},getAvailableNextNodes(isChatMode: boolean) {const nodes = isChatMode ? ALL_CHAT_AVAILABLE_BLOCKS : ALL_COMPLETION_AVAILABLE_BLOCKS- return nodes.filter(type => type !== BlockEnum.VariableAssigner)+ return nodes},checkValid(payload: IfElseNodeType, t: any) {let errorMessages = ''diff --git a/web/app/components/workflow/nodes/if-else/use-config.ts b/web/app/components/workflow/nodes/if-else/use-config.tsindex dc38d3773ce..b20a5b56ea9 100644--- a/web/app/components/workflow/nodes/if-else/use-config.ts+++ b/web/app/components/workflow/nodes/if-else/use-config.ts@@ -3,6 +3,7 @@ import produce from 'immer'import type { Var } from '../../types'import { VarType } from '../../types'import { getVarType } from '../_base/components/variable/utils'+import useNodeInfo from '../_base/hooks/use-node-info'import { LogicalOperator } from './types'import type { Condition, IfElseNodeType } from './types'import useNodeCrud from '@/app/components/workflow/nodes/_base/hooks/use-node-crud'@@ -15,8 +16,11 @@ import {const useConfig = (id: string, payload: IfElseNodeType) => {const { nodesReadOnly: readOnly } = useNodesReadOnly()const { getBeforeNodesInSameBranch } = useWorkflow()+ const {+ parentNode,+ } = useNodeInfo(id)const isChatMode = useIsChatMode()- const availableNodes = getBeforeNodesInSameBranch(id)+ const beforeNodes = getBeforeNodesInSameBranch(id)const { inputs, setInputs } = useNodeCrud<IfElseNodeType>(id, payload)@@ -51,7 +55,12 @@ const useConfig = (id: string, payload: IfElseNodeType) => {}, [])const varTypesList = (inputs.conditions || []).map((condition) => {- return getVarType(condition.variable_selector, availableNodes, isChatMode)+ return getVarType({+ parentNode,+ valueSelector: condition.variable_selector,+ availableNodes: beforeNodes,+ isChatMode,+ })})return {diff --git a/web/app/components/workflow/nodes/index.tsx b/web/app/components/workflow/nodes/index.tsxindex 2214df03522..a79651af700 100644--- a/web/app/components/workflow/nodes/index.tsx+++ b/web/app/components/workflow/nodes/index.tsx@@ -8,16 +8,18 @@ import {import BaseNode from './_base/node'import BasePanel from './_base/panel'-const CustomNode = memo((props: NodeProps) => {+const CustomNode = (props: NodeProps) => {const nodeData = props.dataconst NodeComponent = NodeComponentMap[nodeData.type]return (- <BaseNode { ...props }>- <NodeComponent />- </BaseNode>+ <>+ <BaseNode { ...props }>+ <NodeComponent />+ </BaseNode>+ </>)-})+}CustomNode.displayName = 'CustomNode'export const Panel = memo((props: Node) => {diff --git a/web/app/components/workflow/nodes/iteration/add-block.tsx b/web/app/components/workflow/nodes/iteration/add-block.tsxnew file mode 100644index 00000000000..ec774bb459a--- /dev/null+++ b/web/app/components/workflow/nodes/iteration/add-block.tsx@@ -0,0 +1,128 @@+import {+ memo,+ useCallback,+} from 'react'+import produce from 'immer'+import cn from 'classnames'+import { useStoreApi } from 'reactflow'+import { useTranslation } from 'react-i18next'+import {+ generateNewNode,+} from '../../utils'+import {+ useAvailableBlocks,+ useNodesReadOnly,+} from '../../hooks'+import { NODES_INITIAL_DATA } from '../../constants'+import InsertBlock from './insert-block'+import type { IterationNodeType } from './types'+import BlockSelector from '@/app/components/workflow/block-selector'+import { Plus } from '@/app/components/base/icons/src/vender/line/general'+import { IterationStart } from '@/app/components/base/icons/src/vender/workflow'+import type {+ OnSelectBlock,+} from '@/app/components/workflow/types'+import {+ BlockEnum,+} from '@/app/components/workflow/types'+import TooltipPlus from '@/app/components/base/tooltip-plus'++type AddBlockProps = {+ iterationNodeId: string+ iterationNodeData: IterationNodeType+}+const AddBlock = ({+ iterationNodeId,+ iterationNodeData,+}: AddBlockProps) => {+ const { t } = useTranslation()+ const store = useStoreApi()+ const { nodesReadOnly } = useNodesReadOnly()+ const { availableNextBlocks } = useAvailableBlocks(BlockEnum.Start, true)+ const { availablePrevBlocks } = useAvailableBlocks(iterationNodeData.startNodeType, true)++ const handleSelect = useCallback<OnSelectBlock>((type, toolDefaultValue) => {+ const {+ getNodes,+ setNodes,+ } = store.getState()+ const nodes = getNodes()+ const nodesWithSameType = nodes.filter(node => node.data.type === type)+ const newNode = generateNewNode({+ data: {+ ...NODES_INITIAL_DATA[type],+ title: nodesWithSameType.length > 0 ? `${t(`workflow.blocks.${type}`)} ${nodesWithSameType.length + 1}` : t(`workflow.blocks.${type}`),+ ...(toolDefaultValue || {}),+ isIterationStart: true,+ isInIteration: true,+ iteration_id: iterationNodeId,+ },+ position: {+ x: 117,+ y: 85,+ },+ zIndex: 1001,+ parentId: iterationNodeId,+ extent: 'parent',+ })+ const newNodes = produce(nodes, (draft) => {+ draft.forEach((node) => {+ if (node.id === iterationNodeId) {+ node.data._children = [newNode.id]+ node.data.start_node_id = newNode.id+ node.data.startNodeType = newNode.data.type+ }+ })+ draft.push(newNode)+ })+ setNodes(newNodes)+ }, [store, t, iterationNodeId])++ const renderTriggerElement = useCallback((open: boolean) => {+ return (+ <div className={cn(+ 'relative inline-flex items-center px-3 h-8 rounded-lg border-[0.5px] border-gray-50 bg-white shadow-xs cursor-pointer hover:bg-gray-200 text-[13px] font-medium text-gray-700',+ `${nodesReadOnly && '!cursor-not-allowed opacity-50'}`,+ open && '!bg-gray-50',+ )}>+ <Plus className='mr-1 w-4 h-4' />+ {t('workflow.common.addBlock')}+ </div>+ )+ }, [nodesReadOnly, t])++ return (+ <div className='absolute top-12 left-6 flex items-center h-8 z-10'>+ <TooltipPlus popupContent={t('workflow.blocks.iteration-start')}>+ <div className='flex items-center justify-center w-6 h-6 rounded-full border-[0.5px] border-black/[0.02] shadow-md bg-primary-500'>+ <IterationStart className='w-4 h-4 text-white' />+ </div>+ </TooltipPlus>+ <div className='group/insert relative w-16 h-0.5 bg-gray-300'>+ {+ iterationNodeData.startNodeType && (+ <InsertBlock+ startNodeId={iterationNodeData.start_node_id}+ availableBlocksTypes={availablePrevBlocks}+ />+ )+ }+ <div className='absolute right-0 top-1/2 -translate-y-1/2 w-0.5 h-2 bg-primary-500'></div>+ </div>+ {+ !iterationNodeData.startNodeType && (+ <BlockSelector+ disabled={nodesReadOnly}+ onSelect={handleSelect}+ trigger={renderTriggerElement}+ triggerInnerClassName='inline-flex'+ popupClassName='!min-w-[256px]'+ availableBlocksTypes={availableNextBlocks}+ />+ )+ }+ </div>+ )+}++export default memo(AddBlock)diff --git a/web/app/components/workflow/nodes/iteration/default.ts b/web/app/components/workflow/nodes/iteration/default.tsnew file mode 100644index 00000000000..43f8a751acb--- /dev/null+++ b/web/app/components/workflow/nodes/iteration/default.ts@@ -0,0 +1,39 @@+import { BlockEnum } from '../../types'+import type { NodeDefault } from '../../types'+import type { IterationNodeType } from './types'+import { ALL_CHAT_AVAILABLE_BLOCKS, ALL_COMPLETION_AVAILABLE_BLOCKS } from '@/app/components/workflow/constants'+const i18nPrefix = 'workflow'++const nodeDefault: NodeDefault<IterationNodeType> = {+ defaultValue: {+ start_node_id: '',+ iterator_selector: [],+ output_selector: [],+ },+ getAvailablePrevNodes(isChatMode: boolean) {+ const nodes = isChatMode+ ? ALL_CHAT_AVAILABLE_BLOCKS+ : ALL_COMPLETION_AVAILABLE_BLOCKS.filter(type => type !== BlockEnum.End)+ return nodes+ },+ getAvailableNextNodes(isChatMode: boolean) {+ const nodes = isChatMode ? ALL_CHAT_AVAILABLE_BLOCKS : ALL_COMPLETION_AVAILABLE_BLOCKS+ return nodes+ },+ checkValid(payload: IterationNodeType, t: any) {+ let errorMessages = ''++ if (!errorMessages && (!payload.iterator_selector || payload.iterator_selector.length === 0))+ errorMessages = t(`${i18nPrefix}.errorMsg.fieldRequired`, { field: t(`${i18nPrefix}.nodes.iteration.input`) })++ if (!errorMessages && (!payload.output_selector || payload.output_selector.length === 0))+ errorMessages = t(`${i18nPrefix}.errorMsg.fieldRequired`, { field: t(`${i18nPrefix}.nodes.iteration.output`) })++ return {+ isValid: !errorMessages,+ errorMessage: errorMessages,+ }+ },+}++export default nodeDefaultdiff --git a/web/app/components/workflow/nodes/iteration/insert-block.tsx b/web/app/components/workflow/nodes/iteration/insert-block.tsxnew file mode 100644index 00000000000..9f74302800e--- /dev/null+++ b/web/app/components/workflow/nodes/iteration/insert-block.tsx@@ -0,0 +1,61 @@+import {+ memo,+ useCallback,+ useState,+} from 'react'+import cn from 'classnames'+import { useNodesInteractions } from '../../hooks'+import type {+ BlockEnum,+ OnSelectBlock,+} from '../../types'+import BlockSelector from '../../block-selector'++type InsertBlockProps = {+ startNodeId: string+ availableBlocksTypes: BlockEnum[]+}+const InsertBlock = ({+ startNodeId,+ availableBlocksTypes,+}: InsertBlockProps) => {+ const [open, setOpen] = useState(false)+ const { handleNodeAdd } = useNodesInteractions()++ const handleOpenChange = useCallback((v: boolean) => {+ setOpen(v)+ }, [])+ const handleInsert = useCallback<OnSelectBlock>((nodeType, toolDefaultValue) => {+ handleNodeAdd(+ {+ nodeType,+ toolDefaultValue,+ },+ {+ nextNodeId: startNodeId,+ nextNodeTargetHandle: 'target',+ },+ )+ }, [startNodeId, handleNodeAdd])++ return (+ <div+ className={cn(+ 'nopan nodrag',+ 'hidden group-hover/insert:block absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2',+ open && '!block',+ )}+ >+ <BlockSelector+ open={open}+ onOpenChange={handleOpenChange}+ asChild+ onSelect={handleInsert}+ availableBlocksTypes={availableBlocksTypes}+ triggerClassName={() => 'hover:scale-125 transition-all'}+ />+ </div>+ )+}++export default memo(InsertBlock)diff --git a/web/app/components/workflow/nodes/iteration/node.tsx b/web/app/components/workflow/nodes/iteration/node.tsxnew file mode 100644index 00000000000..84ad9d48db5--- /dev/null+++ b/web/app/components/workflow/nodes/iteration/node.tsx@@ -0,0 +1,49 @@+import type { FC } from 'react'+import {+ memo,+ useEffect,+} from 'react'+import {+ Background,+ useNodesInitialized,+ useViewport,+} from 'reactflow'+import cn from 'classnames'+import { useNodeIterationInteractions } from './use-interactions'+import type { IterationNodeType } from './types'+import AddBlock from './add-block'+import type { NodeProps } from '@/app/components/workflow/types'++const Node: FC<NodeProps<IterationNodeType>> = ({+ id,+ data,+}) => {+ const { zoom } = useViewport()+ const nodesInitialized = useNodesInitialized()+ const { handleNodeIterationRerender } = useNodeIterationInteractions()++ useEffect(() => {+ if (nodesInitialized)+ handleNodeIterationRerender(id)+ }, [nodesInitialized, id, handleNodeIterationRerender])++ return (+ <div className={cn(+ 'relative min-w-[258px] min-h-[118px] w-full h-full rounded-2xl bg-[#F0F2F7]/90',+ )}>+ <Background+ id={`iteration-background-${id}`}+ className='rounded-2xl !z-0'+ gap={[14 / zoom, 14 / zoom]}+ size={2 / zoom}+ color='#E4E5E7'+ />+ <AddBlock+ iterationNodeId={id}+ iterationNodeData={data}+ />+ </div>+ )+}++export default memo(Node)diff --git a/web/app/components/workflow/nodes/iteration/panel.tsx b/web/app/components/workflow/nodes/iteration/panel.tsxnew file mode 100644index 00000000000..8b6cf26ebb1--- /dev/null+++ b/web/app/components/workflow/nodes/iteration/panel.tsx@@ -0,0 +1,136 @@+import type { FC } from 'react'+import React from 'react'+import { useTranslation } from 'react-i18next'++import VarReferencePicker from '../_base/components/variable/var-reference-picker'+import Split from '../_base/components/split'+import ResultPanel from '../../run/result-panel'+import IterationResultPanel from '../../run/iteration-result-panel'+import type { IterationNodeType } from './types'+import useConfig from './use-config'+import { InputVarType, type NodePanelProps } from '@/app/components/workflow/types'+import Field from '@/app/components/workflow/nodes/_base/components/field'+import BeforeRunForm from '@/app/components/workflow/nodes/_base/components/before-run-form'+import { ArrowNarrowRight } from '@/app/components/base/icons/src/vender/line/arrows'++const i18nPrefix = 'workflow.nodes.iteration'++const Panel: FC<NodePanelProps<IterationNodeType>> = ({+ id,+ data,+}) => {+ const { t } = useTranslation()++ const {+ readOnly,+ inputs,+ filterInputVar,+ handleInputChange,+ childrenNodeVars,+ iterationChildrenNodes,+ handleOutputVarChange,+ isShowSingleRun,+ hideSingleRun,+ isShowIterationDetail,+ backToSingleRun,+ showIterationDetail,+ hideIterationDetail,+ runningStatus,+ handleRun,+ handleStop,+ runResult,+ inputVarValues,+ setInputVarValues,+ usedOutVars,+ iterator,+ setIterator,+ iteratorInputKey,+ iterationRunResult,+ } = useConfig(id, data)++ return (+ <div className='mt-2'>+ <div className='px-4 pb-4 space-y-4'>+ <Field+ title={t(`${i18nPrefix}.input`)}+ >+ <VarReferencePicker+ readonly={readOnly}+ nodeId={id}+ isShowNodeName+ value={inputs.iterator_selector || []}+ onChange={handleInputChange}+ filterVar={filterInputVar}+ />+ </Field>+ </div>+ <Split />+ <div className='mt-2 px-4 pb-4 space-y-4'>+ <Field+ title={t(`${i18nPrefix}.output`)}+ operations={(+ <div className='flex items-center h-[18px] px-1 border border-black/8 rounded-[5px] text-xs font-medium text-gray-500 capitalize'>Array</div>+ )}+ >+ <VarReferencePicker+ readonly={readOnly}+ nodeId={id}+ isShowNodeName+ value={inputs.output_selector || []}+ onChange={handleOutputVarChange}+ availableNodes={iterationChildrenNodes}+ availableVars={childrenNodeVars}+ />+ </Field>+ </div>+ {isShowSingleRun && (+ <BeforeRunForm+ nodeName={inputs.title}+ onHide={hideSingleRun}+ forms={[+ {+ inputs: [...usedOutVars],+ values: inputVarValues,+ onChange: setInputVarValues,+ },+ {+ label: t(`${i18nPrefix}.input`)!,+ inputs: [{+ label: '',+ variable: iteratorInputKey,+ type: InputVarType.iterator,+ required: false,+ }],+ values: { [iteratorInputKey]: iterator },+ onChange: keyValue => setIterator((keyValue as any)[iteratorInputKey]),+ },+ ]}+ runningStatus={runningStatus}+ onRun={handleRun}+ onStop={handleStop}+ result={+ <div className='mt-3'>+ <div className='px-4'>+ <div className='flex items-center h-[34px] justify-between px-3 bg-gray-100 border-[0.5px] border-gray-200 rounded-lg cursor-pointer' onClick={showIterationDetail}>+ <div className='leading-[18px] text-[13px] font-medium text-gray-700'>{t(`${i18nPrefix}.iteration`, { count: iterationRunResult.length })}</div>+ <ArrowNarrowRight className='w-3.5 h-3.5 text-gray-500' />+ </div>+ <Split className='mt-3' />+ </div>+ <ResultPanel {...runResult} showSteps={false} />+ </div>+ }+ />+ )}+ {isShowIterationDetail && (+ <IterationResultPanel+ onBack={backToSingleRun}+ onHide={hideIterationDetail}+ list={iterationRunResult}+ />+ )}+ </div>+ )+}++export default React.memo(Panel)diff --git a/web/app/components/workflow/nodes/iteration/types.ts b/web/app/components/workflow/nodes/iteration/types.tsnew file mode 100644index 00000000000..7d2a47dadcf--- /dev/null+++ b/web/app/components/workflow/nodes/iteration/types.ts@@ -0,0 +1,15 @@+import type {+ BlockEnum,+ CommonNodeType,+ ValueSelector,+ VarType,+} from '@/app/components/workflow/types'++export type IterationNodeType = CommonNodeType & {+ startNodeType?: BlockEnum+ start_node_id: string // start node id in the iteration+ iteration_id?: string+ iterator_selector: ValueSelector+ output_selector: ValueSelector+ output_type: VarType // output type.+}diff --git a/web/app/components/workflow/nodes/iteration/use-config.ts b/web/app/components/workflow/nodes/iteration/use-config.tsnew file mode 100644index 00000000000..58fa6a2a13e--- /dev/null+++ b/web/app/components/workflow/nodes/iteration/use-config.ts@@ -0,0 +1,215 @@+import { useCallback } from 'react'+import produce from 'immer'+import { useBoolean } from 'ahooks'+import {+ useIsChatMode,+ useIsNodeInIteration,+ useNodesReadOnly,+ useWorkflow,+} from '../../hooks'+import { VarType } from '../../types'+import type { ValueSelector, Var } from '../../types'+import useNodeCrud from '../_base/hooks/use-node-crud'+import { getNodeInfoById, getNodeUsedVarPassToServerKey, getNodeUsedVars, isSystemVar, toNodeOutputVars } from '../_base/components/variable/utils'+import useOneStepRun from '../_base/hooks/use-one-step-run'+import type { IterationNodeType } from './types'+import type { VarType as VarKindType } from '@/app/components/workflow/nodes/tool/types'++const DELIMITER = '@@@@@'+const useConfig = (id: string, payload: IterationNodeType) => {+ const { nodesReadOnly: readOnly } = useNodesReadOnly()+ const { isNodeInIteration } = useIsNodeInIteration(id)+ const isChatMode = useIsChatMode()++ const { inputs, setInputs } = useNodeCrud<IterationNodeType>(id, payload)++ const filterInputVar = useCallback((varPayload: Var) => {+ return [VarType.array, VarType.arrayString, VarType.arrayNumber, VarType.arrayObject].includes(varPayload.type)+ }, [])++ const handleInputChange = useCallback((input: ValueSelector | string) => {+ const newInputs = produce(inputs, (draft) => {+ draft.iterator_selector = input as ValueSelector || []+ })+ setInputs(newInputs)+ }, [inputs, setInputs])++ // output+ const { getIterationNodeChildren, getBeforeNodesInSameBranch } = useWorkflow()+ const beforeNodes = getBeforeNodesInSameBranch(id)+ const iterationChildrenNodes = getIterationNodeChildren(id)+ const canChooseVarNodes = [...beforeNodes, ...iterationChildrenNodes]+ const childrenNodeVars = toNodeOutputVars(iterationChildrenNodes, isChatMode)++ const handleOutputVarChange = useCallback((output: ValueSelector | string, _varKindType: VarKindType, varInfo?: Var) => {+ const newInputs = produce(inputs, (draft) => {+ draft.output_selector = output as ValueSelector || []+ const outputItemType = varInfo?.type || VarType.string++ draft.output_type = ({+ [VarType.string]: VarType.arrayString,+ [VarType.number]: VarType.arrayNumber,+ [VarType.object]: VarType.arrayObject,+ } as Record<VarType, VarType>)[outputItemType] || VarType.arrayString+ })+ setInputs(newInputs)+ }, [inputs, setInputs])++ // single run+ const iteratorInputKey = `${id}.input_selector`+ const {+ isShowSingleRun,+ showSingleRun,+ hideSingleRun,+ toVarInputs,+ runningStatus,+ handleRun: doHandleRun,+ handleStop,+ runInputData,+ setRunInputData,+ runResult,+ iterationRunResult,+ } = useOneStepRun<IterationNodeType>({+ id,+ data: inputs,+ iteratorInputKey,+ defaultRunInputData: {+ [iteratorInputKey]: [''],+ },+ })++ const [isShowIterationDetail, {+ setTrue: doShowIterationDetail,+ setFalse: doHideIterationDetail,+ }] = useBoolean(false)++ const hideIterationDetail = useCallback(() => {+ hideSingleRun()+ doHideIterationDetail()+ }, [doHideIterationDetail, hideSingleRun])++ const showIterationDetail = useCallback(() => {+ doShowIterationDetail()+ }, [doShowIterationDetail])++ const backToSingleRun = useCallback(() => {+ hideIterationDetail()+ showSingleRun()+ }, [hideIterationDetail, showSingleRun])++ const { usedOutVars, allVarObject } = (() => {+ const vars: ValueSelector[] = []+ const varObjs: Record<string, boolean> = {}+ const allVarObject: Record<string, {+ inSingleRunPassedKey: string+ }> = {}+ iterationChildrenNodes.forEach((node) => {+ const nodeVars = getNodeUsedVars(node).filter(item => item && item.length > 0)+ nodeVars.forEach((varSelector) => {+ if (varSelector[0] === id) { // skip iteration node itself variable: item, index+ return+ }+ const isInIteration = isNodeInIteration(varSelector[0])+ if (isInIteration) // not pass iteration inner variable+ return++ const varSectorStr = varSelector.join('.')+ if (!varObjs[varSectorStr]) {+ varObjs[varSectorStr] = true+ vars.push(varSelector)+ }+ let passToServerKeys = getNodeUsedVarPassToServerKey(node, varSelector)+ if (typeof passToServerKeys === 'string')+ passToServerKeys = [passToServerKeys]++ passToServerKeys.forEach((key: string, index: number) => {+ allVarObject[[varSectorStr, node.id, index].join(DELIMITER)] = {+ inSingleRunPassedKey: key,+ }+ })+ })+ })+ const res = toVarInputs(vars.map((item) => {+ const varInfo = getNodeInfoById(canChooseVarNodes, item[0])+ return {+ label: {+ nodeType: varInfo?.data.type,+ nodeName: varInfo?.data.title || canChooseVarNodes[0]?.data.title, // default start node title+ variable: isSystemVar(item) ? item.join('.') : item[item.length - 1],+ },+ variable: `${item.join('.')}`,+ value_selector: item,+ }+ }))+ return {+ usedOutVars: res,+ allVarObject,+ }+ })()++ const handleRun = useCallback((data: Record<string, any>) => {+ const formattedData: Record<string, any> = {}+ Object.keys(allVarObject).forEach((key) => {+ const [varSectorStr, nodeId] = key.split(DELIMITER)+ formattedData[`${nodeId}.${allVarObject[key].inSingleRunPassedKey}`] = data[varSectorStr]+ })+ formattedData[iteratorInputKey] = data[iteratorInputKey]+ doHandleRun(formattedData)+ }, [allVarObject, doHandleRun, iteratorInputKey])++ const inputVarValues = (() => {+ const vars: Record<string, any> = {}+ Object.keys(runInputData)+ .filter(key => ![iteratorInputKey].includes(key))+ .forEach((key) => {+ vars[key] = runInputData[key]+ })+ return vars+ })()++ const setInputVarValues = useCallback((newPayload: Record<string, any>) => {+ const newVars = {+ ...newPayload,+ [iteratorInputKey]: runInputData[iteratorInputKey],+ }+ setRunInputData(newVars)+ }, [iteratorInputKey, runInputData, setRunInputData])++ const iterator = runInputData[iteratorInputKey]+ const setIterator = useCallback((newIterator: string[]) => {+ setRunInputData({+ ...runInputData,+ [iteratorInputKey]: newIterator,+ })+ }, [iteratorInputKey, runInputData, setRunInputData])++ return {+ readOnly,+ inputs,+ filterInputVar,+ handleInputChange,+ childrenNodeVars,+ iterationChildrenNodes,+ handleOutputVarChange,+ isShowSingleRun,+ showSingleRun,+ hideSingleRun,+ isShowIterationDetail,+ showIterationDetail,+ hideIterationDetail,+ backToSingleRun,+ runningStatus,+ handleRun,+ handleStop,+ runResult,+ inputVarValues,+ setInputVarValues,+ usedOutVars,+ iterator,+ setIterator,+ iteratorInputKey,+ iterationRunResult,+ }+}++export default useConfigdiff --git a/web/app/components/workflow/nodes/iteration/use-interactions.ts b/web/app/components/workflow/nodes/iteration/use-interactions.tsnew file mode 100644index 00000000000..219c8e731f4--- /dev/null+++ b/web/app/components/workflow/nodes/iteration/use-interactions.ts@@ -0,0 +1,142 @@+import { useCallback } from 'react'+import produce from 'immer'+import { useTranslation } from 'react-i18next'+import { useStoreApi } from 'reactflow'+import type {+ BlockEnum,+ Node,+} from '../../types'+import { generateNewNode } from '../../utils'+import {+ ITERATION_PADDING,+ NODES_INITIAL_DATA,+} from '../../constants'++export const useNodeIterationInteractions = () => {+ const { t } = useTranslation()+ const store = useStoreApi()++ const handleNodeIterationRerender = useCallback((nodeId: string) => {+ const {+ getNodes,+ setNodes,+ } = store.getState()++ const nodes = getNodes()+ const currentNode = nodes.find(n => n.id === nodeId)!+ const childrenNodes = nodes.filter(n => n.parentId === nodeId)+ let rightNode: Node+ let bottomNode: Node++ childrenNodes.forEach((n) => {+ if (rightNode) {+ if (n.position.x + n.width! > rightNode.position.x + rightNode.width!)+ rightNode = n+ }+ else {+ rightNode = n+ }+ if (bottomNode) {+ if (n.position.y + n.height! > bottomNode.position.y + bottomNode.height!)+ bottomNode = n+ }+ else {+ bottomNode = n+ }+ })++ const widthShouldExtend = rightNode! && currentNode.width! < rightNode.position.x + rightNode.width!+ const heightShouldExtend = bottomNode! && currentNode.height! < bottomNode.position.y + bottomNode.height!++ if (widthShouldExtend || heightShouldExtend) {+ const newNodes = produce(nodes, (draft) => {+ draft.forEach((n) => {+ if (n.id === nodeId) {+ if (widthShouldExtend) {+ n.data.width = rightNode.position.x + rightNode.width! + ITERATION_PADDING.right+ n.width = rightNode.position.x + rightNode.width! + ITERATION_PADDING.right+ }+ if (heightShouldExtend) {+ n.data.height = bottomNode.position.y + bottomNode.height! + ITERATION_PADDING.bottom+ n.height = bottomNode.position.y + bottomNode.height! + ITERATION_PADDING.bottom+ }+ }+ })+ })++ setNodes(newNodes)+ }+ }, [store])++ const handleNodeIterationChildDrag = useCallback((node: Node) => {+ const { getNodes } = store.getState()+ const nodes = getNodes()++ const restrictPosition: { x?: number; y?: number } = { x: undefined, y: undefined }++ if (node.data.isInIteration) {+ const parentNode = nodes.find(n => n.id === node.parentId)++ if (parentNode) {+ if (node.position.y < ITERATION_PADDING.top)+ restrictPosition.y = ITERATION_PADDING.top+ if (node.position.x < ITERATION_PADDING.left)+ restrictPosition.x = ITERATION_PADDING.left+ if (node.position.x + node.width! > parentNode!.width! - ITERATION_PADDING.right)+ restrictPosition.x = parentNode!.width! - ITERATION_PADDING.right - node.width!+ if (node.position.y + node.height! > parentNode!.height! - ITERATION_PADDING.bottom)+ restrictPosition.y = parentNode!.height! - ITERATION_PADDING.bottom - node.height!+ }+ }++ return {+ restrictPosition,+ }+ }, [store])++ const handleNodeIterationChildSizeChange = useCallback((nodeId: string) => {+ const { getNodes } = store.getState()+ const nodes = getNodes()+ const currentNode = nodes.find(n => n.id === nodeId)!+ const parentId = currentNode.parentId++ if (parentId)+ handleNodeIterationRerender(parentId)+ }, [store, handleNodeIterationRerender])++ const handleNodeIterationChildrenCopy = useCallback((nodeId: string, newNodeId: string) => {+ const { getNodes } = store.getState()+ const nodes = getNodes()+ const childrenNodes = nodes.filter(n => n.parentId === nodeId)++ return childrenNodes.map((child, index) => {+ const childNodeType = child.data.type as BlockEnum+ const nodesWithSameType = nodes.filter(node => node.data.type === childNodeType)+ const newNode = generateNewNode({+ data: {+ ...NODES_INITIAL_DATA[childNodeType],+ ...child.data,+ selected: false,+ _isBundled: false,+ _connectedSourceHandleIds: [],+ _connectedTargetHandleIds: [],+ title: nodesWithSameType.length > 0 ? `${t(`workflow.blocks.${childNodeType}`)} ${nodesWithSameType.length + 1}` : t(`workflow.blocks.${childNodeType}`),+ },+ position: child.position,+ positionAbsolute: child.positionAbsolute,+ parentId: newNodeId,+ extent: child.extent,+ zIndex: child.zIndex,+ })+ newNode.id = `${newNodeId}${newNode.id + index}`+ return newNode+ })+ }, [store, t])++ return {+ handleNodeIterationRerender,+ handleNodeIterationChildDrag,+ handleNodeIterationChildSizeChange,+ handleNodeIterationChildrenCopy,+ }+}diff --git a/web/app/components/workflow/nodes/llm/components/config-prompt.tsx b/web/app/components/workflow/nodes/llm/components/config-prompt.tsxindex 5bea2005b2b..3b4c452de34 100644--- a/web/app/components/workflow/nodes/llm/components/config-prompt.tsx+++ b/web/app/components/workflow/nodes/llm/components/config-prompt.tsx@@ -62,7 +62,7 @@ const ConfigPrompt: FC<Props> = ({: []const {availableVars,- availableNodes,+ availableNodesWithParent,} = useAvailableVarList(nodeId, {onlyLeafNodeVar: false,filterVar,@@ -186,7 +186,7 @@ const ConfigPrompt: FC<Props> = ({isShowContext={isShowContext}hasSetBlockStatus={hasSetBlockStatus}availableVars={availableVars}- availableNodes={availableNodes}+ availableNodes={availableNodesWithParent}varList={varList}handleAddVariable={handleAddVariable}/>@@ -218,7 +218,7 @@ const ConfigPrompt: FC<Props> = ({isShowContext={isShowContext}hasSetBlockStatus={hasSetBlockStatus}nodesOutputVars={availableVars}- availableNodes={availableNodes}+ availableNodes={availableNodesWithParent}isSupportJinjaeditionType={(payload as PromptItem).edition_type}varList={varList}diff --git a/web/app/components/workflow/nodes/llm/panel.tsx b/web/app/components/workflow/nodes/llm/panel.tsxindex 89a5a0eb2b9..eaf69ecfc8b 100644--- a/web/app/components/workflow/nodes/llm/panel.tsx+++ b/web/app/components/workflow/nodes/llm/panel.tsx@@ -45,7 +45,7 @@ const Panel: FC<NodePanelProps<LLMNodeType>> = ({filterInputVar,filterVar,availableVars,- availableNodes,+ availableNodesWithParent,isShowVars,handlePromptChange,handleAddEmptyVariable,@@ -234,7 +234,7 @@ const Panel: FC<NodePanelProps<LLMNodeType>> = ({isChatModelhasSetBlockStatus={hasSetBlockStatus}nodesOutputVars={availableVars}- availableNodes={availableNodes}+ availableNodes={availableNodesWithParent}/>{inputs.memory.query_prompt_template && !inputs.memory.query_prompt_template.includes('{{#sys.query#}}') && (diff --git a/web/app/components/workflow/nodes/llm/use-config.ts b/web/app/components/workflow/nodes/llm/use-config.tsindex a93bf63e47a..f70c395b0bc 100644--- a/web/app/components/workflow/nodes/llm/use-config.ts+++ b/web/app/components/workflow/nodes/llm/use-config.ts@@ -337,7 +337,7 @@ const useConfig = (id: string, payload: LLMNodeType) => {const {availableVars,- availableNodes,+ availableNodesWithParent,} = useAvailableVarList(id, {onlyLeafNodeVar: false,filterVar,@@ -437,7 +437,7 @@ const useConfig = (id: string, payload: LLMNodeType) => {filterInputVar,filterVar,availableVars,- availableNodes,+ availableNodesWithParent,handlePromptChange,handleMemoryChange,handleSyeQueryChange,diff --git a/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/import-from-tool.tsx b/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/import-from-tool.tsxnew file mode 100644index 00000000000..7a1c524da1e--- /dev/null+++ b/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/import-from-tool.tsx@@ -0,0 +1,92 @@+'use client'+import type { FC } from 'react'+import {+ memo,+ useCallback,+} from 'react'+import cn from 'classnames'+import { useTranslation } from 'react-i18next'+import BlockSelector from '../../../../block-selector'+import type { Param, ParamType } from '../../types'+import { useStore } from '@/app/components/workflow/store'+import type { ToolDefaultValue } from '@/app/components/workflow/block-selector/types'+import type { ToolParameter } from '@/app/components/tools/types'+import { CollectionType } from '@/app/components/tools/types'+import type { BlockEnum } from '@/app/components/workflow/types'+import { useLanguage } from '@/app/components/header/account-setting/model-provider-page/hooks'++const i18nPrefix = 'workflow.nodes.parameterExtractor'++type Props = {+ onImport: (params: Param[]) => void+}++function toParmExactParams(toolParams: ToolParameter[], lan: string): Param[] {+ return toolParams.map((item) => {+ return {+ name: item.name,+ type: item.type as ParamType,+ required: item.required,+ description: item.llm_description,+ options: item.options?.map(option => option.label[lan] || option.label.en_US) || [],+ }+ })+}+const ImportFromTool: FC<Props> = ({+ onImport,+}) => {+ const { t } = useTranslation()+ const language = useLanguage()++ const buildInTools = useStore(s => s.buildInTools)+ const customTools = useStore(s => s.customTools)+ const workflowTools = useStore(s => s.workflowTools)++ const handleSelectTool = useCallback((_type: BlockEnum, toolInfo?: ToolDefaultValue) => {+ const { provider_id, provider_type, tool_name } = toolInfo!+ const currentTools = (() => {+ switch (provider_type) {+ case CollectionType.builtIn:+ return buildInTools+ case CollectionType.custom:+ return customTools+ case CollectionType.workflow:+ return workflowTools+ default:+ return []+ }+ })()+ const currCollection = currentTools.find(item => item.id === provider_id)+ const currTool = currCollection?.tools.find(tool => tool.name === tool_name)+ const toExactParams = (currTool?.parameters || []).filter((item: any) => item.form === 'llm')+ const formattedParams = toParmExactParams(toExactParams, language)+ onImport(formattedParams)+ }, [buildInTools, customTools, language, onImport, workflowTools])++ const renderTrigger = useCallback((open: boolean) => {+ return (+ <div>+ <div className={cn(+ 'flex items-center h-6 px-2 cursor-pointer rounded-md hover:bg-gray-100 text-xs font-medium text-gray-500',+ open && 'bg-gray-100',+ )}>+ {t(`${i18nPrefix}.importFromTool`)}+ </div>+ </div>+ )+ }, [t])++ return (+ <BlockSelector+ placement='bottom-end'+ offset={{+ mainAxis: 4,+ crossAxis: 52,+ }}+ trigger={renderTrigger}+ onSelect={handleSelectTool}+ noBlocks+ />+ )+}+export default memo(ImportFromTool)diff --git a/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/item.tsx b/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/item.tsxnew file mode 100644index 00000000000..abbff414965--- /dev/null+++ b/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/item.tsx@@ -0,0 +1,59 @@+'use client'+import type { FC } from 'react'+import React from 'react'+import { useTranslation } from 'react-i18next'+import type { Param } from '../../types'+import { Variable02 } from '@/app/components/base/icons/src/vender/solid/development'+import { Edit03, Trash03 } from '@/app/components/base/icons/src/vender/line/general'+const i18nPrefix = 'workflow.nodes.parameterExtractor'++type Props = {+ payload: Param+ onEdit: () => void+ onDelete: () => void+}++const Item: FC<Props> = ({+ payload,+ onEdit,+ onDelete,+}) => {+ const { t } = useTranslation()++ return (+ <div className='relative px-2.5 py-2 rounded-lg bg-white border-[0.5px] border-gray-200 hover:shadow-xs group'>+ <div className='flex justify-between'>+ <div className='flex items-center'>+ <Variable02 className='w-3.5 h-3.5 text-primary-500' />+ <div className='ml-1 text-[13px] font-medium text-gray-900'>{payload.name}</div>+ <div className='ml-2 text-xs font-normal text-gray-500 capitalize'>{payload.type}</div>+ </div>+ {payload.required && (+ <div className='uppercase leading-4 text-xs font-normal text-gray-500'>{t(`${i18nPrefix}.addExtractParameterContent.required`)}</div>+ )}+ </div>+ <div className='mt-0.5 leading-[18px] text-xs font-normal text-gray-500'>{payload.description}</div>+ <div+ className='group-hover:flex absolute top-0 right-1 hidden h-full items-center w-[119px] justify-end space-x-1 rounded-lg'+ style={{+ background: 'linear-gradient(270deg, #FFF 49.99%, rgba(255, 255, 255, 0.00) 98.1%)',+ }}+ >+ <div+ className='p-1 cursor-pointer rounded-md hover:bg-black/5'+ onClick={onEdit}+ >+ <Edit03 className='w-4 h-4 text-gray-500' />+ </div>++ <div+ className='p-1 cursor-pointer rounded-md hover:bg-black/5'+ onClick={onDelete}+ >+ <Trash03 className='w-4 h-4 text-gray-500' />+ </div>+ </div>+ </div>+ )+}+export default React.memo(Item)diff --git a/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/list.tsx b/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/list.tsxnew file mode 100644index 00000000000..eacb78e7f4c--- /dev/null+++ b/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/list.tsx@@ -0,0 +1,85 @@+'use client'+import type { FC } from 'react'+import React, { useCallback, useState } from 'react'+import { useTranslation } from 'react-i18next'+import { useBoolean } from 'ahooks'+import type { Param } from '../../types'+import ListNoDataPlaceholder from '../../../_base/components/list-no-data-placeholder'+import Item from './item'+import EditParam from './update'+import type { MoreInfo } from '@/app/components/workflow/types'++const i18nPrefix = 'workflow.nodes.parameterExtractor'++type Props = {+ readonly: boolean+ list: Param[]+ onChange: (list: Param[], moreInfo?: MoreInfo) => void+}++const List: FC<Props> = ({+ list,+ onChange,+}) => {+ const { t } = useTranslation()+ const [isShowEditModal, {+ setTrue: showEditModal,+ setFalse: hideEditModal,+ }] = useBoolean(false)++ const handleItemChange = useCallback((index: number) => {+ return (payload: Param, moreInfo?: MoreInfo) => {+ const newList = list.map((item, i) => {+ if (i === index)+ return payload++ return item+ })+ onChange(newList, moreInfo)+ hideEditModal()+ }+ }, [hideEditModal, list, onChange])++ const [currEditItemIndex, setCurrEditItemIndex] = useState<number>(-1)++ const handleItemEdit = useCallback((index: number) => {+ return () => {+ setCurrEditItemIndex(index)+ showEditModal()+ }+ }, [showEditModal])++ const handleItemDelete = useCallback((index: number) => {+ return () => {+ const newList = list.filter((_, i) => i !== index)+ onChange(newList)+ }+ }, [list, onChange])++ if (list.length === 0) {+ return (+ <ListNoDataPlaceholder >{t(`${i18nPrefix}.extractParametersNotSet`)}</ListNoDataPlaceholder>+ )+ }+ return (+ <div className='space-y-1'>+ {list.map((item, index) => (+ <Item+ key={index}+ payload={item}+ onDelete={handleItemDelete(index)}+ onEdit={handleItemEdit(index)}+ />+ ))}+ {isShowEditModal && (+ <EditParam+ type='edit'+ payload={list[currEditItemIndex]}+ onSave={handleItemChange(currEditItemIndex)}+ onCancel={hideEditModal}+ />+ )}+ </div>+ )+}+export default React.memo(List)diff --git a/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/update.tsx b/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/update.tsxnew file mode 100644index 00000000000..47561943132--- /dev/null+++ b/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/update.tsx@@ -0,0 +1,193 @@+'use client'+import type { FC } from 'react'+import React, { useCallback, useState } from 'react'+import { useBoolean } from 'ahooks'+import { useTranslation } from 'react-i18next'+import cn from 'classnames'+import type { Param } from '../../types'+import { ParamType } from '../../types'+import AddButton from '@/app/components/base/button/add-button'+import Modal from '@/app/components/base/modal'+import Button from '@/app/components/base/button'+import Field from '@/app/components/app/configuration/config-var/config-modal/field'+import Select from '@/app/components/base/select'+import Switch from '@/app/components/base/switch'+import Toast from '@/app/components/base/toast'+import ConfigSelect from '@/app/components/app/configuration/config-var/config-select'+import { ChangeType, type MoreInfo } from '@/app/components/workflow/types'+import { checkKeys } from '@/utils/var'++const i18nPrefix = 'workflow.nodes.parameterExtractor'+const errorI18nPrefix = 'workflow.errorMsg'+const inputClassName = 'w-full px-3 text-sm leading-9 text-gray-900 border-0 rounded-lg grow h-9 bg-gray-100 focus:outline-none focus:ring-1 focus:ring-inset focus:ring-gray-200'++const DEFAULT_PARAM: Param = {+ name: '',+ type: ParamType.string,+ description: '',+ required: false,+}++type Props = {+ type: 'add' | 'edit'+ payload?: Param+ onSave: (payload: Param, moreInfo?: MoreInfo) => void+ onCancel?: () => void+}++const TYPES = [ParamType.string, ParamType.number, ParamType.arrayString, ParamType.arrayNumber, ParamType.arrayObject]++const AddExtractParameter: FC<Props> = ({+ type,+ payload,+ onSave,+ onCancel,+}) => {+ const { t } = useTranslation()+ const isAdd = type === 'add'+ const [param, setParam] = useState<Param>(isAdd ? DEFAULT_PARAM : payload as Param)+ const [renameInfo, setRenameInfo] = useState<MoreInfo | undefined>(undefined)+ const handleParamChange = useCallback((key: string) => {+ return (value: any) => {+ if (key === 'name') {+ const { isValid, errorKey, errorMessageKey } = checkKeys([value], true)+ if (!isValid) {+ Toast.notify({+ type: 'error',+ message: t(`appDebug.varKeyError.${errorMessageKey}`, { key: errorKey }),+ })+ return+ }+ }+ setRenameInfo(key === 'name'+ ? {+ type: ChangeType.changeVarName,+ payload: {+ beforeKey: param.name,+ afterKey: value,+ },+ }+ : undefined)+ setParam((prev) => {+ return {+ ...prev,+ [key]: value,+ }+ })+ }+ }, [param.name, t])++ const [isShowModal, {+ setTrue: doShowModal,+ setFalse: doHideModal,+ }] = useBoolean(!isAdd)++ const hideModal = useCallback(() => {+ doHideModal()+ onCancel?.()+ }, [onCancel, doHideModal])++ const showAddModal = useCallback(() => {+ if (isAdd)+ setParam(DEFAULT_PARAM)++ doShowModal()+ }, [isAdd, doShowModal])++ const checkValid = useCallback(() => {+ let errMessage = ''+ if (!param.name)+ errMessage = t(`${errorI18nPrefix}.fieldRequired`, { field: t(`${i18nPrefix}.addExtractParameterContent.name`) })+ if (!errMessage && param.type === ParamType.select && (!param.options || param.options.length === 0))+ errMessage = t(`${errorI18nPrefix}.fieldRequired`, { field: t('appDebug.variableConig.options') })+ if (!errMessage && !param.description)+ errMessage = t(`${errorI18nPrefix}.fieldRequired`, { field: t(`${i18nPrefix}.addExtractParameterContent.description`) })++ if (errMessage) {+ Toast.notify({+ type: 'error',+ message: errMessage,+ })+ return false+ }+ return true+ }, [param, t])++ const handleSave = useCallback(() => {+ if (!checkValid())+ return++ onSave(param, renameInfo)+ hideModal()+ }, [checkValid, onSave, param, hideModal, renameInfo])++ return (+ <div>+ {isAdd && (+ <AddButton className='mx-1' onClick={showAddModal} />+ )}+ {isShowModal && (+ <Modal+ title={t(`${i18nPrefix}.addExtractParameter`)}+ isShow+ onClose={hideModal}+ className='!w-[400px] !max-w-[400px] !p-4'+ wrapperClassName='!z-[100]'+ >+ <div>+ <div className='space-y-2'>+ <Field title={t(`${i18nPrefix}.addExtractParameterContent.name`)}>+ <input+ type='text'+ className={inputClassName}+ value={param.name}+ onChange={e => handleParamChange('name')(e.target.value)}+ placeholder={t(`${i18nPrefix}.addExtractParameterContent.namePlaceholder`)!}+ />+ </Field>+ <Field title={t(`${i18nPrefix}.addExtractParameterContent.type`)}>+ <Select+ defaultValue={param.type}+ allowSearch={false}+ bgClassName='bg-gray-100'+ onSelect={v => handleParamChange('type')(v.value)}+ optionClassName='capitalize'+ items={+ TYPES.map(type => ({+ value: type,+ name: type,+ }))+ }+ />+ </Field>+ {param.type === ParamType.select && (+ <Field title={t('appDebug.variableConig.options')}>+ <ConfigSelect options={param.options || []} onChange={handleParamChange('options')} />+ </Field>+ )}+ <Field title={t(`${i18nPrefix}.addExtractParameterContent.description`)}>+ <textarea+ className={cn(inputClassName, '!h-[80px]')}+ value={param.description}+ onChange={e => handleParamChange('description')(e.target.value)}+ placeholder={t(`${i18nPrefix}.addExtractParameterContent.descriptionPlaceholder`)!}+ />+ </Field>+ <Field title={t(`${i18nPrefix}.addExtractParameterContent.required`)}>+ <>+ <div className='mb-1.5 leading-[18px] text-xs font-normal text-gray-500'>{t(`${i18nPrefix}.addExtractParameterContent.requiredContent`)}</div>+ <Switch size='l' defaultValue={param.required} onChange={handleParamChange('required')} />+ </>+ </Field>+ </div>+ <div className='mt-4 flex justify-end space-x-2'>+ <Button className='flex !h-8 !w-[95px] text-[13px] font-medium text-gray-700' onClick={hideModal} >{t('common.operation.cancel')}</Button>+ <Button className='flex !h-8 !w-[95px] text-[13px] font-medium' type='primary' onClick={handleSave} >{isAdd ? t('common.operation.add') : t('common.operation.save')}</Button>+ </div>+ </div>+ </Modal>+ )}+ </div>+ )+}+export default React.memo(AddExtractParameter)diff --git a/web/app/components/workflow/nodes/parameter-extractor/components/reasoning-mode-picker.tsx b/web/app/components/workflow/nodes/parameter-extractor/components/reasoning-mode-picker.tsxnew file mode 100644index 00000000000..596bad1ae02--- /dev/null+++ b/web/app/components/workflow/nodes/parameter-extractor/components/reasoning-mode-picker.tsx@@ -0,0 +1,70 @@+'use client'+import type { FC } from 'react'+import React, { useCallback } from 'react'+import cn from 'classnames'+import { useTranslation } from 'react-i18next'+import { ReasoningModeType } from '../types'+import Field from '../../_base/components/field'++const i18nPrefix = 'workflow.nodes.parameterExtractor'++type ItemProps = {+ isChosen: boolean+ text: string+ onClick: () => void+}++const Item: FC<ItemProps> = ({+ isChosen,+ text,+ onClick,+}) => {+ return (+ <div+ className={cn(isChosen ? 'border-[1.5px] border-primary-400 bg-white' : 'border border-gray-100 bg-gray-25', 'grow w-0 shrink-0 flex items-center h-8 justify-center rounded-lg cursor-pointer text-[13px] font-normal text-gray-900')}+ onClick={() => !isChosen ? onClick() : () => { }}+ >+ {text}+ </div>+ )+}++type Props = {+ type: ReasoningModeType+ onChange: (type: ReasoningModeType) => void+}++const ReasoningModePicker: FC<Props> = ({+ type,+ onChange,+}) => {+ const { t } = useTranslation()++ const handleChange = useCallback((type: ReasoningModeType) => {+ return () => {+ onChange(type)+ }+ }, [onChange])++ return (+ <Field+ title={t(`${i18nPrefix}.reasoningMode`)}+ tooltip={t(`${i18nPrefix}.reasoningModeTip`)!}+ >+ <div className='flex space-x-1'>+ <Item+ isChosen={type === ReasoningModeType.functionCall}+ text='Function/Tool Calling'+ onClick={handleChange(ReasoningModeType.functionCall)}+ />+ <Item+ isChosen={type === ReasoningModeType.prompt}+ text='Prompt'+ onClick={handleChange(ReasoningModeType.prompt)}+ />+ </div>+ </Field>++ )+}+export default React.memo(ReasoningModePicker)diff --git a/web/app/components/workflow/nodes/parameter-extractor/default.ts b/web/app/components/workflow/nodes/parameter-extractor/default.tsnew file mode 100644index 00000000000..c1f5776ad5d--- /dev/null+++ b/web/app/components/workflow/nodes/parameter-extractor/default.ts@@ -0,0 +1,64 @@+import { BlockEnum } from '../../types'+import type { NodeDefault } from '../../types'+import { type ParameterExtractorNodeType, ReasoningModeType } from './types'+import { ALL_CHAT_AVAILABLE_BLOCKS, ALL_COMPLETION_AVAILABLE_BLOCKS } from '@/app/components/workflow/constants'+const i18nPrefix = 'workflow'++const nodeDefault: NodeDefault<ParameterExtractorNodeType> = {+ defaultValue: {+ query: [],+ model: {+ provider: '',+ name: '',+ mode: 'chat',+ completion_params: {+ temperature: 0.7,+ },+ },+ reasoning_mode: ReasoningModeType.prompt,+ },+ getAvailablePrevNodes(isChatMode: boolean) {+ const nodes = isChatMode+ ? ALL_CHAT_AVAILABLE_BLOCKS+ : ALL_COMPLETION_AVAILABLE_BLOCKS.filter(type => type !== BlockEnum.End)+ return nodes+ },+ getAvailableNextNodes(isChatMode: boolean) {+ const nodes = isChatMode ? ALL_CHAT_AVAILABLE_BLOCKS : ALL_COMPLETION_AVAILABLE_BLOCKS+ return nodes+ },+ checkValid(payload: ParameterExtractorNodeType, t: any) {+ let errorMessages = ''+ if (!errorMessages && (!payload.query || payload.query.length === 0))+ errorMessages = t(`${i18nPrefix}.errorMsg.fieldRequired`, { field: t(`${i18nPrefix}.nodes.parameterExtractor.inputVar`) })++ if (!errorMessages && !payload.model.provider)+ errorMessages = t(`${i18nPrefix}.errorMsg.fieldRequired`, { field: t(`${i18nPrefix}.nodes.parameterExtractor.model`) })++ if (!errorMessages && (!payload.parameters || payload.parameters.length === 0))+ errorMessages = t(`${i18nPrefix}.errorMsg.fieldRequired`, { field: t(`${i18nPrefix}.nodes.parameterExtractor.extractParameters`) })++ if (!errorMessages) {+ payload.parameters.forEach((param) => {+ if (errorMessages)+ return+ if (!param.name) {+ errorMessages = t(`${i18nPrefix}.errorMsg.fieldRequired`, { field: t(`${i18nPrefix}.nodes.parameterExtractor.addExtractParameterContent.namePlaceholder`) })+ return+ }+ if (!param.type) {+ errorMessages = t(`${i18nPrefix}.errorMsg.fieldRequired`, { field: t(`${i18nPrefix}.nodes.parameterExtractor.addExtractParameterContent.typePlaceholder`) })+ return+ }+ if (!param.description)+ errorMessages = t(`${i18nPrefix}.errorMsg.fieldRequired`, { field: t(`${i18nPrefix}.nodes.parameterExtractor.addExtractParameterContent.descriptionPlaceholder`) })+ })+ }+ return {+ isValid: !errorMessages,+ errorMessage: errorMessages,+ }+ },+}++export default nodeDefaultdiff --git a/web/app/components/workflow/nodes/parameter-extractor/node.tsx b/web/app/components/workflow/nodes/parameter-extractor/node.tsxnew file mode 100644index 00000000000..8a1b08e9244--- /dev/null+++ b/web/app/components/workflow/nodes/parameter-extractor/node.tsx@@ -0,0 +1,31 @@+import type { FC } from 'react'+import React from 'react'+import type { ParameterExtractorNodeType } from './types'+import {+ useTextGenerationCurrentProviderAndModelAndModelList,+} from '@/app/components/header/account-setting/model-provider-page/hooks'+import ModelSelector from '@/app/components/header/account-setting/model-provider-page/model-selector'+import type { NodeProps } from '@/app/components/workflow/types'++const Node: FC<NodeProps<ParameterExtractorNodeType>> = ({+ data,+}) => {+ const { provider, name: modelId } = data.model || {}+ const {+ textGenerationModelList,+ } = useTextGenerationCurrentProviderAndModelAndModelList()+ const hasSetModel = provider && modelId+ return (+ <div className='mb-1 px-3 py-1'>+ {hasSetModel && (+ <ModelSelector+ defaultModel={{ provider, model: modelId }}+ modelList={textGenerationModelList}+ readonly+ />+ )}+ </div>+ )+}++export default React.memo(Node)diff --git a/web/app/components/workflow/nodes/parameter-extractor/panel.tsx b/web/app/components/workflow/nodes/parameter-extractor/panel.tsxnew file mode 100644index 00000000000..1a185c5af12--- /dev/null+++ b/web/app/components/workflow/nodes/parameter-extractor/panel.tsx@@ -0,0 +1,227 @@+import type { FC } from 'react'+import React from 'react'+import { useTranslation } from 'react-i18next'+import MemoryConfig from '../_base/components/memory-config'+import VarReferencePicker from '../_base/components/variable/var-reference-picker'+import Editor from '../_base/components/prompt/editor'+import ResultPanel from '../../run/result-panel'+import useConfig from './use-config'+import type { ParameterExtractorNodeType } from './types'+import ExtractParameter from './components/extract-parameter/list'+import ImportFromTool from './components/extract-parameter/import-from-tool'+import AddExtractParameter from './components/extract-parameter/update'+import ReasoningModePicker from './components/reasoning-mode-picker'+import Field from '@/app/components/workflow/nodes/_base/components/field'+import Split from '@/app/components/workflow/nodes/_base/components/split'+import ModelParameterModal from '@/app/components/header/account-setting/model-provider-page/model-parameter-modal'+import OutputVars, { VarItem } from '@/app/components/workflow/nodes/_base/components/output-vars'+import { InputVarType, type NodePanelProps } from '@/app/components/workflow/types'+import TooltipPlus from '@/app/components/base/tooltip-plus'+import { HelpCircle } from '@/app/components/base/icons/src/vender/line/general'+import BeforeRunForm from '@/app/components/workflow/nodes/_base/components/before-run-form'+import { VarType } from '@/app/components/workflow/types'++const i18nPrefix = 'workflow.nodes.parameterExtractor'+const i18nCommonPrefix = 'workflow.common'++const Panel: FC<NodePanelProps<ParameterExtractorNodeType>> = ({+ id,+ data,+}) => {+ const { t } = useTranslation()++ const {+ readOnly,+ inputs,+ handleInputVarChange,+ filterVar,+ isChatModel,+ isChatMode,+ isCompletionModel,+ handleModelChanged,+ handleImportFromTool,+ handleCompletionParamsChange,+ addExtractParameter,+ handleExactParamsChange,+ handleInstructionChange,+ hasSetBlockStatus,+ handleMemoryChange,+ isSupportFunctionCall,+ handleReasoningModeChange,+ availableVars,+ availableNodesWithParent,+ inputVarValues,+ varInputs,+ isShowSingleRun,+ hideSingleRun,+ runningStatus,+ handleRun,+ handleStop,+ runResult,+ setInputVarValues,+ } = useConfig(id, data)++ const model = inputs.model++ return (+ <div className='mt-2'>+ <div className='px-4 pb-4 space-y-4'>+ <Field+ title={t(`${i18nPrefix}.inputVar`)}+ >+ <>+ <VarReferencePicker+ readonly={readOnly}+ nodeId={id}+ isShowNodeName+ value={inputs.query || []}+ onChange={handleInputVarChange}+ filterVar={filterVar}+ />+ </>+ </Field>+ <Field+ title={t(`${i18nCommonPrefix}.model`)}+ >+ <ModelParameterModal+ popupClassName='!w-[387px]'+ isInWorkflow+ isAdvancedMode={true}+ mode={model?.mode}+ provider={model?.provider}+ completionParams={model?.completion_params}+ modelId={model?.name}+ setModel={handleModelChanged}+ onCompletionParamsChange={handleCompletionParamsChange}+ hideDebugWithMultipleModel+ debugWithMultipleModel={false}+ readonly={readOnly}+ />+ </Field>+ <Field+ title={t(`${i18nPrefix}.extractParameters`)}+ operations={+ !readOnly+ ? (+ <div className='flex items-center space-x-1'>+ {!readOnly && (+ <ImportFromTool onImport={handleImportFromTool} />+ )}+ {!readOnly && (<div className='w-px h-3 bg-gray-200'></div>)}+ <AddExtractParameter type='add' onSave={addExtractParameter} />+ </div>+ )+ : undefined+ }+ >+ <ExtractParameter+ readonly={readOnly}+ list={inputs.parameters || []}+ onChange={handleExactParamsChange}+ />+ </Field>+ <Editor+ title={+ <div className='flex items-center space-x-1'>+ <span className='uppercase'>{t(`${i18nPrefix}.instruction`)}</span>+ <TooltipPlus popupContent={+ <div className='w-[120px]'>+ {t(`${i18nPrefix}.instructionTip`)}+ </div>}>+ <HelpCircle className='w-3.5 h-3.5 ml-0.5 text-gray-400' />+ </TooltipPlus>+ </div>+ }+ value={inputs.instruction}+ onChange={handleInstructionChange}+ readOnly={readOnly}+ isChatModel={isChatModel}+ isChatApp={isChatMode}+ isShowContext={false}+ hasSetBlockStatus={hasSetBlockStatus}+ nodesOutputVars={availableVars}+ availableNodes={availableNodesWithParent}+ />+ <Field+ title={t(`${i18nPrefix}.advancedSetting`)}+ supportFold+ >+ <>++ {/* Memory */}+ {isChatMode && (+ <div className='mt-4'>+ <MemoryConfig+ readonly={readOnly}+ config={{ data: inputs.memory }}+ onChange={handleMemoryChange}+ canSetRoleName={isCompletionModel}+ />+ </div>+ )}+ {isSupportFunctionCall && (+ <div className='mt-2'>+ <ReasoningModePicker+ type={inputs.reasoning_mode}+ onChange={handleReasoningModeChange}+ />+ </div>+ )}+ </>+ </Field>++ </div>+ {inputs.parameters?.length > 0 && (<>+ <Split />+ <div className='px-4 pt-4 pb-2'>+ <OutputVars>+ <>+ <VarItem+ name='__is_success'+ type={VarType.number}+ description={t(`${i18nPrefix}.isSuccess`)}+ />+ <VarItem+ name='__reason'+ type={VarType.string}+ description={t(`${i18nPrefix}.errorReason`)}+ />+ {inputs.parameters.map((param, index) => (+ <VarItem+ key={index}+ name={param.name}+ type={param.type}+ description={param.description}+ />+ ))}+ </>+ </OutputVars>+ </div>+ </>)}+ {isShowSingleRun && (+ <BeforeRunForm+ nodeName={inputs.title}+ onHide={hideSingleRun}+ forms={[+ {+ inputs: [{+ label: t(`${i18nPrefix}.inputVar`)!,+ variable: 'query',+ type: InputVarType.paragraph,+ required: true,+ }, ...varInputs],+ values: inputVarValues,+ onChange: setInputVarValues,+ },+ ]}+ runningStatus={runningStatus}+ onRun={handleRun}+ onStop={handleStop}+ result={<ResultPanel {...runResult} showSteps={false} />}+ />+ )}+ </div>+ )+}++export default React.memo(Panel)diff --git a/web/app/components/workflow/nodes/parameter-extractor/types.ts b/web/app/components/workflow/nodes/parameter-extractor/types.tsnew file mode 100644index 00000000000..5038bd8a9cd--- /dev/null+++ b/web/app/components/workflow/nodes/parameter-extractor/types.ts@@ -0,0 +1,33 @@+import type { CommonNodeType, Memory, ModelConfig, ValueSelector } from '@/app/components/workflow/types'++export enum ParamType {+ string = 'string',+ number = 'number',+ bool = 'bool',+ select = 'select',+ arrayString = 'array[string]',+ arrayNumber = 'array[number]',+ arrayObject = 'array[object]',+}++export type Param = {+ name: string+ type: ParamType+ options?: string[]+ description: string+ required?: boolean+}++export enum ReasoningModeType {+ prompt = 'prompt',+ functionCall = 'function_call',+}++export type ParameterExtractorNodeType = CommonNodeType & {+ model: ModelConfig+ query: ValueSelector+ reasoning_mode: ReasoningModeType+ parameters: Param[]+ instruction: string+ memory?: Memory+}diff --git a/web/app/components/workflow/nodes/parameter-extractor/use-config.ts b/web/app/components/workflow/nodes/parameter-extractor/use-config.tsnew file mode 100644index 00000000000..ddfaed507e3--- /dev/null+++ b/web/app/components/workflow/nodes/parameter-extractor/use-config.ts@@ -0,0 +1,258 @@+import { useCallback, useEffect, useRef, useState } from 'react'+import produce from 'immer'+import type { Memory, MoreInfo, ValueSelector, Var } from '../../types'+import { ChangeType, VarType } from '../../types'+import { useStore } from '../../store'+import {+ useIsChatMode,+ useNodesReadOnly,+ useWorkflow,+} from '../../hooks'+import useOneStepRun from '../_base/hooks/use-one-step-run'+import type { Param, ParameterExtractorNodeType, ReasoningModeType } from './types'+import { useModelListAndDefaultModelAndCurrentProviderAndModel, useTextGenerationCurrentProviderAndModelAndModelList } from '@/app/components/header/account-setting/model-provider-page/hooks'+import {+ ModelFeatureEnum,+ ModelTypeEnum,+} from '@/app/components/header/account-setting/model-provider-page/declarations'+import useNodeCrud from '@/app/components/workflow/nodes/_base/hooks/use-node-crud'+import { checkHasQueryBlock } from '@/app/components/base/prompt-editor/constants'+import useAvailableVarList from '@/app/components/workflow/nodes/_base/hooks/use-available-var-list'++const useConfig = (id: string, payload: ParameterExtractorNodeType) => {+ const { nodesReadOnly: readOnly } = useNodesReadOnly()+ const { handleOutVarRenameChange } = useWorkflow()+ const isChatMode = useIsChatMode()++ const defaultConfig = useStore(s => s.nodesDefaultConfigs)[payload.type]++ const [defaultRolePrefix, setDefaultRolePrefix] = useState<{ user: string; assistant: string }>({ user: '', assistant: '' })+ const { inputs, setInputs: doSetInputs } = useNodeCrud<ParameterExtractorNodeType>(id, payload)+ const inputRef = useRef(inputs)++ const setInputs = useCallback((newInputs: ParameterExtractorNodeType) => {+ if (newInputs.memory && !newInputs.memory.role_prefix) {+ const newPayload = produce(newInputs, (draft) => {+ draft.memory!.role_prefix = defaultRolePrefix+ })+ doSetInputs(newPayload)+ inputRef.current = newPayload+ return+ }+ doSetInputs(newInputs)+ inputRef.current = newInputs+ }, [doSetInputs, defaultRolePrefix])++ const filterVar = useCallback((varPayload: Var) => {+ return [VarType.string].includes(varPayload.type)+ }, [])++ const handleInputVarChange = useCallback((newInputVar: ValueSelector | string) => {+ const newInputs = produce(inputs, (draft) => {+ draft.query = newInputVar as ValueSelector || []+ })+ setInputs(newInputs)+ }, [inputs, setInputs])++ const handleExactParamsChange = useCallback((newParams: Param[], moreInfo?: MoreInfo) => {+ const newInputs = produce(inputs, (draft) => {+ draft.parameters = newParams+ })+ setInputs(newInputs)++ if (moreInfo && moreInfo?.type === ChangeType.changeVarName && moreInfo.payload)+ handleOutVarRenameChange(id, [id, moreInfo.payload.beforeKey], [id, moreInfo.payload.afterKey!])+ }, [handleOutVarRenameChange, id, inputs, setInputs])++ const addExtractParameter = useCallback((payload: Param) => {+ const newInputs = produce(inputs, (draft) => {+ if (!draft.parameters)+ draft.parameters = []+ draft.parameters.push(payload)+ })+ setInputs(newInputs)+ }, [inputs, setInputs])++ // model+ const model = inputs.model || {+ provider: '',+ name: '',+ mode: 'chat',+ completion_params: {+ temperature: 0.7,+ },+ }+ const modelMode = inputs.model?.mode+ const isChatModel = modelMode === 'chat'++ const isCompletionModel = !isChatModel++ const appendDefaultPromptConfig = useCallback((draft: ParameterExtractorNodeType, defaultConfig: any, _passInIsChatMode?: boolean) => {+ const promptTemplates = defaultConfig.prompt_templates+ if (!isChatModel) {+ setDefaultRolePrefix({+ user: promptTemplates.completion_model.conversation_histories_role.user_prefix,+ assistant: promptTemplates.completion_model.conversation_histories_role.assistant_prefix,+ })+ }+ }, [isChatModel])++ // const [modelChanged, setModelChanged] = useState(false)+ const {+ currentProvider,+ currentModel,+ } = useModelListAndDefaultModelAndCurrentProviderAndModel(ModelTypeEnum.textGeneration)++ const handleModelChanged = useCallback((model: { provider: string; modelId: string; mode?: string }) => {+ const newInputs = produce(inputRef.current, (draft) => {+ draft.model.provider = model.provider+ draft.model.name = model.modelId+ draft.model.mode = model.mode!+ const isModeChange = model.mode !== inputRef.current.model?.mode+ if (isModeChange && defaultConfig && Object.keys(defaultConfig).length > 0)+ appendDefaultPromptConfig(draft, defaultConfig, model.mode === 'chat')+ })+ setInputs(newInputs)+ // setModelChanged(true)+ }, [setInputs, defaultConfig, appendDefaultPromptConfig])++ useEffect(() => {+ if (currentProvider?.provider && currentModel?.model && !model.provider) {+ handleModelChanged({+ provider: currentProvider?.provider,+ modelId: currentModel?.model,+ mode: currentModel?.model_properties?.mode as string,+ })+ }+ }, [model?.provider, currentProvider, currentModel, handleModelChanged])++ const {+ currentModel: currModel,+ } = useTextGenerationCurrentProviderAndModelAndModelList(+ {+ provider: model.provider,+ model: model.name,+ },+ )++ const isSupportFunctionCall = currModel?.features?.includes(ModelFeatureEnum.toolCall) || currModel?.features?.includes(ModelFeatureEnum.multiToolCall)++ const filterInputVar = useCallback((varPayload: Var) => {+ return [VarType.number, VarType.string].includes(varPayload.type)+ }, [])++ const {+ availableVars,+ availableNodesWithParent,+ } = useAvailableVarList(id, {+ onlyLeafNodeVar: false,+ filterVar: filterInputVar,+ })++ const handleCompletionParamsChange = useCallback((newParams: Record<string, any>) => {+ const newInputs = produce(inputs, (draft) => {+ draft.model.completion_params = newParams+ })+ setInputs(newInputs)+ }, [inputs, setInputs])++ const handleInstructionChange = useCallback((newInstruction: string) => {+ const newInputs = produce(inputs, (draft) => {+ draft.instruction = newInstruction+ })+ setInputs(newInputs)+ }, [inputs, setInputs])++ const hasSetBlockStatus = {+ history: false,+ query: isChatMode ? checkHasQueryBlock(inputs.instruction) : false,+ context: false,+ }++ const handleMemoryChange = useCallback((newMemory?: Memory) => {+ const newInputs = produce(inputs, (draft) => {+ draft.memory = newMemory+ })+ setInputs(newInputs)+ }, [inputs, setInputs])++ const handleReasoningModeChange = useCallback((newReasoningMode: ReasoningModeType) => {+ const newInputs = produce(inputs, (draft) => {+ draft.reasoning_mode = newReasoningMode+ })+ setInputs(newInputs)+ }, [inputs, setInputs])++ const handleImportFromTool = useCallback((params: Param[]) => {+ const newInputs = produce(inputs, (draft) => {+ draft.parameters = params+ })+ setInputs(newInputs)+ }, [inputs, setInputs])++ // single run+ const {+ isShowSingleRun,+ hideSingleRun,+ getInputVars,+ runningStatus,+ handleRun,+ handleStop,+ runInputData,+ setRunInputData,+ runResult,+ } = useOneStepRun<ParameterExtractorNodeType>({+ id,+ data: inputs,+ defaultRunInputData: {+ query: '',+ },+ })++ const varInputs = getInputVars([inputs.instruction])+ const inputVarValues = (() => {+ const vars: Record<string, any> = {}+ Object.keys(runInputData)+ .forEach((key) => {+ vars[key] = runInputData[key]+ })+ return vars+ })()++ const setInputVarValues = useCallback((newPayload: Record<string, any>) => {+ setRunInputData(newPayload)+ }, [setRunInputData])++ return {+ readOnly,+ handleInputVarChange,+ filterVar,+ isChatMode,+ inputs,+ isChatModel,+ isCompletionModel,+ handleModelChanged,+ handleCompletionParamsChange,+ handleImportFromTool,+ handleExactParamsChange,+ addExtractParameter,+ handleInstructionChange,+ hasSetBlockStatus,+ availableVars,+ availableNodesWithParent,+ isSupportFunctionCall,+ handleReasoningModeChange,+ handleMemoryChange,+ varInputs,+ inputVarValues,+ isShowSingleRun,+ hideSingleRun,+ runningStatus,+ handleRun,+ handleStop,+ runResult,+ setInputVarValues,+ }+}++export default useConfigdiff --git a/web/app/components/workflow/nodes/question-classifier/components/advanced-setting.tsx b/web/app/components/workflow/nodes/question-classifier/components/advanced-setting.tsxindex 644e0de2056..f95dfce31ab 100644--- a/web/app/components/workflow/nodes/question-classifier/components/advanced-setting.tsx+++ b/web/app/components/workflow/nodes/question-classifier/components/advanced-setting.tsx@@ -5,6 +5,8 @@ import { useTranslation } from 'react-i18next'import TextEditor from '../../_base/components/editor/text-editor'import MemoryConfig from '../../_base/components/memory-config'import type { Memory } from '@/app/components/workflow/types'+import TooltipPlus from '@/app/components/base/tooltip-plus'+import { HelpCircle } from '@/app/components/base/icons/src/vender/line/general'const i18nPrefix = 'workflow.nodes.questionClassifiers'type Props = {@@ -30,7 +32,17 @@ const AdvancedSetting: FC<Props> = ({<><TextEditorisInNode- title={t(`${i18nPrefix}.instruction`)!}+ title={+ <div className='flex items-center space-x-1'>+ <span className='uppercase'>{t(`${i18nPrefix}.instruction`)}</span>+ <TooltipPlus popupContent={+ <div className='w-[120px]'>+ {t(`${i18nPrefix}.instructionTip`)}+ </div>}>+ <HelpCircle className='w-3.5 h-3.5 ml-0.5 text-gray-400' />+ </TooltipPlus>+ </div>+ }value={instruction}onChange={onInstructionChange}minHeight={160}diff --git a/web/app/components/workflow/nodes/question-classifier/default.ts b/web/app/components/workflow/nodes/question-classifier/default.tsindex 4279d1d4b07..bd3f6658684 100644--- a/web/app/components/workflow/nodes/question-classifier/default.ts+++ b/web/app/components/workflow/nodes/question-classifier/default.ts@@ -35,7 +35,7 @@ const nodeDefault: NodeDefault<QuestionClassifierNodeType> = {},getAvailableNextNodes(isChatMode: boolean) {const nodes = isChatMode ? ALL_CHAT_AVAILABLE_BLOCKS : ALL_COMPLETION_AVAILABLE_BLOCKS- return nodes.filter(type => type !== BlockEnum.VariableAssigner)+ return nodes},checkValid(payload: QuestionClassifierNodeType, t: any) {let errorMessages = ''diff --git a/web/app/components/workflow/nodes/tool/components/input-var-list.tsx b/web/app/components/workflow/nodes/tool/components/input-var-list.tsxindex c25fde498d4..a4faf7d0814 100644--- a/web/app/components/workflow/nodes/tool/components/input-var-list.tsx+++ b/web/app/components/workflow/nodes/tool/components/input-var-list.tsx@@ -36,17 +36,6 @@ const InputVarList: FC<Props> = ({filterVar,}) => {const language = useLanguage()-- // const valueList = (() => {- // const list = []- // Object.keys(value).forEach((key) => {- // list.push({- // variable: key,- // ...value[key],- // })- // })- // })()-const { t } = useTranslation()const { availableVars, availableNodes } = useAvailableVarList(nodeId, {onlyLeafNodeVar: false,@@ -54,6 +43,14 @@ const InputVarList: FC<Props> = ({return [VarType.string, VarType.number].includes(varPayload.type)},})+ const paramType = (type: string) => {+ if (type === FormTypeEnum.textNumber)+ return 'Number'+ else if (type === FormTypeEnum.files)+ return 'Files'+ else+ return 'String'+ }const handleNotMixedTypeChange = useCallback((variable: string) => {return (varValue: ValueSelector | string, varKindType: VarKindType) => {@@ -125,16 +122,18 @@ const InputVarList: FC<Props> = ({tooltip,}, index) => {const varInput = value[variable]- const isString = type !== FormTypeEnum.textNumber+ const isNumber = type === FormTypeEnum.textNumber+ const isFile = type === FormTypeEnum.files+ const isString = type !== FormTypeEnum.textNumber && type !== FormTypeEnum.filesreturn (<div key={variable} className='space-y-1'><div className='flex items-center h-[18px] space-x-2'><span className='text-[13px] font-medium text-gray-900'>{label[language] || label.en_US}</span>- <span className='text-xs font-normal text-gray-500'>{!isString ? 'Number' : 'String'}</span>+ <span className='text-xs font-normal text-gray-500'>{paramType(type)}</span>{required && <span className='leading-[18px] text-xs font-normal text-[#EC4A0A]'>Required</span>}</div>- {isString- ? (<Input+ {isString && (+ <InputclassName={cn(inputsIsFocus[variable] ? 'shadow-xs bg-gray-50 border-gray-300' : 'bg-gray-100 border-gray-100', 'rounded-lg px-3 py-[6px] border')}value={varInput?.value as string || ''}onChange={handleMixedTypeChange(variable)}@@ -144,21 +143,33 @@ const InputVarList: FC<Props> = ({onFocusChange={handleInputFocus(variable)}placeholder={t('workflow.nodes.http.insertVarPlaceholder')!}placeholderClassName='!leading-[21px]'- />)- : (- <VarReferencePicker- readonly={readOnly}- isShowNodeName- nodeId={nodeId}- value={varInput?.type === VarKindType.constant ? (varInput?.value || '') : (varInput?.value || [])}- onChange={handleNotMixedTypeChange(variable)}- onOpen={handleOpen(index)}- isSupportConstantValue={isSupportConstantValue}- defaultVarKindType={varInput?.type}- filterVar={filterVar}- />- )}-+ />+ )}+ {isNumber && (+ <VarReferencePicker+ readonly={readOnly}+ isShowNodeName+ nodeId={nodeId}+ value={varInput?.type === VarKindType.constant ? (varInput?.value || '') : (varInput?.value || [])}+ onChange={handleNotMixedTypeChange(variable)}+ onOpen={handleOpen(index)}+ isSupportConstantValue={isSupportConstantValue}+ defaultVarKindType={varInput?.type}+ filterVar={filterVar}+ />+ )}+ {isFile && (+ <VarReferencePicker+ readonly={readOnly}+ isShowNodeName+ nodeId={nodeId}+ value={varInput?.type === VarKindType.constant ? (varInput?.value || '') : (varInput?.value || [])}+ onChange={handleNotMixedTypeChange(variable)}+ onOpen={handleOpen(index)}+ defaultVarKindType={VarKindType.variable}+ filterVar={(varPayload: Var) => varPayload.type === VarType.arrayFile}+ />+ )}{tooltip && <div className='leading-[18px] text-xs font-normal text-gray-600'>{tooltip[language] || tooltip.en_US}</div>}</div>)diff --git a/web/app/components/workflow/nodes/tool/types.ts b/web/app/components/workflow/nodes/tool/types.tsindex b44950bf005..1ed6f9c3736 100644--- a/web/app/components/workflow/nodes/tool/types.ts+++ b/web/app/components/workflow/nodes/tool/types.ts@@ -1,3 +1,4 @@+import type { CollectionType } from '@/app/components/tools/types'import type { CommonNodeType, ValueSelector } from '@/app/components/workflow/types'export enum VarType {@@ -13,7 +14,7 @@ export type ToolVarInputs = Record<string, {export type ToolNodeType = CommonNodeType & {provider_id: string- provider_type: 'builtin'+ provider_type: CollectionTypeprovider_name: stringtool_name: stringtool_label: stringdiff --git a/web/app/components/workflow/nodes/tool/use-config.ts b/web/app/components/workflow/nodes/tool/use-config.tsindex 5d499e77827..df8ad47985b 100644--- a/web/app/components/workflow/nodes/tool/use-config.ts+++ b/web/app/components/workflow/nodes/tool/use-config.ts@@ -34,7 +34,20 @@ const useConfig = (id: string, payload: ToolNodeType) => {const isBuiltIn = provider_type === CollectionType.builtInconst buildInTools = useStore(s => s.buildInTools)const customTools = useStore(s => s.customTools)- const currentTools = isBuiltIn ? buildInTools : customTools+ const workflowTools = useStore(s => s.workflowTools)++ const currentTools = (() => {+ switch (provider_type) {+ case CollectionType.builtIn:+ return buildInTools+ case CollectionType.custom:+ return customTools+ case CollectionType.workflow:+ return workflowTools+ default:+ return []+ }+ })()const currCollection = currentTools.find(item => item.id === provider_id)// Authdiff --git a/web/app/components/workflow/nodes/variable-assigner/components/add-variable/index.tsx b/web/app/components/workflow/nodes/variable-assigner/components/add-variable/index.tsxnew file mode 100644index 00000000000..6cd165d5d4e--- /dev/null+++ b/web/app/components/workflow/nodes/variable-assigner/components/add-variable/index.tsx@@ -0,0 +1,87 @@+import {+ memo,+ useCallback,+} from 'react'+import cn from 'classnames'+import { useVariableAssigner } from '../../hooks'+import type { VariableAssignerNodeType } from '../../types'+import {+ PortalToFollowElem,+ PortalToFollowElemContent,+ PortalToFollowElemTrigger,+} from '@/app/components/base/portal-to-follow-elem'+import { Plus02 } from '@/app/components/base/icons/src/vender/line/general'+import AddVariablePopup from '@/app/components/workflow/nodes/_base/components/add-variable-popup'+import type {+ NodeOutPutVar,+ ValueSelector,+ Var,+} from '@/app/components/workflow/types'++export type AddVariableProps = {+ open: boolean+ onOpenChange: (open: boolean) => void+ variableAssignerNodeId: string+ variableAssignerNodeData: VariableAssignerNodeType+ availableVars: NodeOutPutVar[]+ handleId?: string+}+const AddVariable = ({+ open,+ onOpenChange,+ availableVars,+ variableAssignerNodeId,+ variableAssignerNodeData,+ handleId,+}: AddVariableProps) => {+ const { handleAssignVariableValueChange } = useVariableAssigner()++ const handleSelectVariable = useCallback((v: ValueSelector, varDetail: Var) => {+ handleAssignVariableValueChange(+ variableAssignerNodeId,+ v,+ varDetail,+ handleId,+ )+ onOpenChange(false)+ }, [handleAssignVariableValueChange, variableAssignerNodeId, handleId, onOpenChange])++ return (+ <div className={cn(+ 'hidden group-hover:flex absolute top-0 left-0 z-10 pointer-events-none',+ open && '!flex',+ variableAssignerNodeData.selected && '!flex',+ )}>+ <PortalToFollowElem+ placement={'left-start'}+ offset={{+ mainAxis: 4,+ crossAxis: -60,+ }}+ open={open}+ onOpenChange={onOpenChange}+ >+ <PortalToFollowElemTrigger+ onClick={() => onOpenChange(!open)}+ >+ <div+ className={cn(+ 'flex items-center justify-center',+ 'w-4 h-4 rounded-full bg-primary-600 cursor-pointer z-10',+ )}+ >+ <Plus02 className='w-2.5 h-2.5 text-white' />+ </div>+ </PortalToFollowElemTrigger>+ <PortalToFollowElemContent className='z-[1000]'>+ <AddVariablePopup+ onSelect={handleSelectVariable}+ availableVars={availableVars}+ />+ </PortalToFollowElemContent>+ </PortalToFollowElem>+ </div>+ )+}++export default memo(AddVariable)diff --git a/web/app/components/workflow/nodes/variable-assigner/components/node-group-item.tsx b/web/app/components/workflow/nodes/variable-assigner/components/node-group-item.tsxnew file mode 100644index 00000000000..18886a79fb2--- /dev/null+++ b/web/app/components/workflow/nodes/variable-assigner/components/node-group-item.tsx@@ -0,0 +1,107 @@+import {+ memo,+ useMemo,+} from 'react'+import cn from 'classnames'+import { useTranslation } from 'react-i18next'+import { useNodes } from 'reactflow'+import { useStore } from '../../../store'+import { BlockEnum } from '../../../types'+import type {+ Node,+ ValueSelector,+ VarType,+} from '../../../types'+import type { VariableAssignerNodeType } from '../types'+import {+ useGetAvailableVars,+ useVariableAssigner,+} from '../hooks'+import { filterVar } from '../utils'+import NodeHandle from './node-handle'+import NodeVariableItem from './node-variable-item'+import { isSystemVar } from '@/app/components/workflow/nodes/_base/components/variable/utils'++const i18nPrefix = 'workflow.nodes.variableAssigner'+type GroupItem = {+ groupEnabled: boolean+ targetHandleId: string+ title: string+ type: string+ variables: ValueSelector[]+ variableAssignerNodeId: string+ variableAssignerNodeData: VariableAssignerNodeType+}+type NodeGroupItemProps = {+ item: GroupItem+}+const NodeGroupItem = ({+ item,+}: NodeGroupItemProps) => {+ const { t } = useTranslation()+ const enteringNodePayload = useStore(s => s.enteringNodePayload)+ const hoveringAssignVariableGroupId = useStore(s => s.hoveringAssignVariableGroupId)+ const nodes: Node[] = useNodes()+ const {+ handleGroupItemMouseEnter,+ handleGroupItemMouseLeave,+ } = useVariableAssigner()+ const getAvailableVars = useGetAvailableVars()+ const outputType = useMemo(() => {+ if (item.targetHandleId === 'target')+ return item.variableAssignerNodeData.output_type++ const group = item.variableAssignerNodeData.advanced_settings?.groups.find(group => group.groupId === item.targetHandleId)+ return group?.output_type || ''+ }, [item.variableAssignerNodeData, item.targetHandleId])+ const availableVars = getAvailableVars(item.variableAssignerNodeId, item.targetHandleId, filterVar(outputType as VarType))+ const showSelectionBorder = enteringNodePayload?.nodeId === item.variableAssignerNodeId && item.groupEnabled && hoveringAssignVariableGroupId === item.targetHandleId+ const connected = item.variableAssignerNodeData._connectedTargetHandleIds?.includes(item.targetHandleId)++ return (+ <div+ className={cn(+ 'relative pt-1 px-1.5 pb-1.5 rounded-lg border border-transparent',+ showSelectionBorder && '!border-primary-600',+ )}+ onMouseEnter={() => handleGroupItemMouseEnter(item.targetHandleId)}+ onMouseLeave={handleGroupItemMouseLeave}+ >+ <div className='flex items-center justify-between h-4 text-[10px] font-medium text-gray-500'>+ <NodeHandle+ connected={connected}+ variableAssignerNodeId={item.variableAssignerNodeId}+ variableAssignerNodeData={item.variableAssignerNodeData}+ handleId={item.targetHandleId}+ availableVars={availableVars}+ />+ <span className='grow uppercase truncate' title={item.title}>{item.title}</span>+ <span className='shrink-0 ml-2'>{item.type}</span>+ </div>+ {+ !item.variables.length && (+ <div className='relative flex items-center px-1 h-[22px] justify-between bg-gray-100 rounded-md space-x-1 text-[10px] font-normal text-gray-400 uppercase'>+ {t(`${i18nPrefix}.varNotSet`)}+ </div>+ )+ }+ {+ !!item.variables.length && item.variables.map((variable = [], index) => {+ const isSystem = isSystemVar(variable)+ const node = isSystem ? nodes.find(node => node.data.type === BlockEnum.Start) : nodes.find(node => node.id === variable[0])+ const varName = isSystem ? `sys.${variable[variable.length - 1]}` : variable.slice(1).join('.')++ return (+ <NodeVariableItem+ key={index}+ node={node as Node}+ varName={varName}+ />+ )+ })+ }+ </div>+ )+}++export default memo(NodeGroupItem)diff --git a/web/app/components/workflow/nodes/variable-assigner/components/node-handle.tsx b/web/app/components/workflow/nodes/variable-assigner/components/node-handle.tsxnew file mode 100644index 00000000000..2edd0c88807--- /dev/null+++ b/web/app/components/workflow/nodes/variable-assigner/components/node-handle.tsx@@ -0,0 +1,69 @@+import type { MouseEvent } from 'react'+import {+ memo,+ useCallback,+ useState,+} from 'react'+import cn from 'classnames'+import {+ Handle,+ Position,+} from 'reactflow'+import type { VariableAssignerNodeType } from '../types'+import AddVariable from './add-variable'+import type { NodeOutPutVar } from '@/app/components/workflow/types'+import { useStore } from '@/app/components/workflow/store'++type NodeHandleProps = {+ handleId?: string+ connected?: boolean+ variableAssignerNodeId: string+ availableVars: NodeOutPutVar[]+ variableAssignerNodeData: VariableAssignerNodeType+}+const NodeHandle = ({+ connected,+ variableAssignerNodeId,+ handleId = 'target',+ availableVars,+ variableAssignerNodeData,+}: NodeHandleProps) => {+ const [open, setOpen] = useState(false)+ const connectingNodePayload = useStore(s => s.connectingNodePayload)+ const isUnConnectable = connectingNodePayload?.handleType === 'source'++ const handleOpenChange = useCallback((v: boolean) => {+ setOpen(v)+ }, [])++ const handleHandleClick = useCallback((e: MouseEvent) => {+ e.stopPropagation()+ setOpen(v => !v)+ }, [])++ return (+ <Handle+ id={handleId}+ type='target'+ onClick={handleHandleClick}+ position={Position.Left}+ isConnectable={!isUnConnectable}+ className={cn(+ '!-left-[13px] !top-1 !w-4 !h-4 !bg-transparent !rounded-none !outline-none !border-none z-[1] !transform-none',+ 'after:absolute after:w-0.5 after:h-2 after:left-[5px] after:top-1 after:bg-primary-500 pointer-events-none',+ !connected && 'after:opacity-0',+ )}+ >+ <AddVariable+ open={open}+ onOpenChange={handleOpenChange}+ variableAssignerNodeId={variableAssignerNodeId}+ variableAssignerNodeData={variableAssignerNodeData}+ handleId={handleId}+ availableVars={availableVars}+ />+ </Handle>+ )+}++export default memo(NodeHandle)diff --git a/web/app/components/workflow/nodes/variable-assigner/components/node-variable-item.tsx b/web/app/components/workflow/nodes/variable-assigner/components/node-variable-item.tsxnew file mode 100644index 00000000000..074d0ccf150--- /dev/null+++ b/web/app/components/workflow/nodes/variable-assigner/components/node-variable-item.tsx@@ -0,0 +1,36 @@+import { memo } from 'react'+import { VarBlockIcon } from '@/app/components/workflow/block-icon'+import { Line3 } from '@/app/components/base/icons/src/public/common'+import { Variable02 } from '@/app/components/base/icons/src/vender/solid/development'+import type { Node } from '@/app/components/workflow/types'+import { BlockEnum } from '@/app/components/workflow/types'++type NodeVariableItemProps = {+ node: Node+ varName: string+}+const NodeVariableItem = ({+ node,+ varName,+}: NodeVariableItemProps) => {+ return (+ <div className='relative flex items-center mt-0.5 h-6 bg-gray-100 rounded-md px-1 text-xs font-normal text-gray-700' >+ <div className='flex items-center'>+ <div className='p-[1px]'>+ <VarBlockIcon+ className='!text-gray-900'+ type={node?.data.type || BlockEnum.Start}+ />+ </div>+ <div className='max-w-[85px] truncate mx-0.5 text-xs font-medium text-gray-700' title={node?.data.title}>{node?.data.title}</div>+ <Line3 className='mr-0.5'></Line3>+ </div>+ <div className='flex items-center text-primary-600'>+ <Variable02 className='w-3.5 h-3.5' />+ <div className='max-w-[75px] truncate ml-0.5 text-xs font-medium' title={varName}>{varName}</div>+ </div>+ </div>+ )+}++export default memo(NodeVariableItem)diff --git a/web/app/components/workflow/nodes/variable-assigner/components/var-group-item.tsx b/web/app/components/workflow/nodes/variable-assigner/components/var-group-item.tsxnew file mode 100644index 00000000000..0381706a649--- /dev/null+++ b/web/app/components/workflow/nodes/variable-assigner/components/var-group-item.tsx@@ -0,0 +1,176 @@+'use client'+import React, { useCallback } from 'react'+import type { ChangeEvent, FC } from 'react'+import { useTranslation } from 'react-i18next'+import produce from 'immer'+import { useBoolean } from 'ahooks'+import type { VarGroupItem as VarGroupItemType } from '../types'+import VarReferencePicker from '../../_base/components/variable/var-reference-picker'+import VarList from '../components/var-list'+import Field from '@/app/components/workflow/nodes/_base/components/field'+import { VarType } from '@/app/components/workflow/types'+import type { NodeOutPutVar, ValueSelector, Var } from '@/app/components/workflow/types'+import { VarType as VarKindType } from '@/app/components/workflow/nodes/tool/types'+import { Trash03 } from '@/app/components/base/icons/src/vender/line/general'+import { Folder } from '@/app/components/base/icons/src/vender/line/files'+import { checkKeys } from '@/utils/var'+import Toast from '@/app/components/base/toast'++const i18nPrefix = 'workflow.nodes.variableAssigner'++type Payload = VarGroupItemType & {+ group_name?: string+}++type Props = {+ readOnly: boolean+ nodeId: string+ payload: Payload+ onChange: (newPayload: Payload) => void+ groupEnabled: boolean+ onGroupNameChange?: (value: string) => void+ canRemove?: boolean+ onRemove?: () => void+ availableVars: NodeOutPutVar[]+}++const VarGroupItem: FC<Props> = ({+ readOnly,+ nodeId,+ payload,+ onChange,+ groupEnabled,+ onGroupNameChange,+ canRemove,+ onRemove,+ availableVars,+}) => {+ const { t } = useTranslation()++ const handleAddVariable = useCallback((value: ValueSelector | string, _varKindType: VarKindType, varInfo?: Var) => {+ const chosenVariables = payload.variables+ if (chosenVariables.some(item => item.join('.') === (value as ValueSelector).join('.')))+ return++ const newPayload = produce(payload, (draft: Payload) => {+ draft.variables.push(value as ValueSelector)+ if (varInfo && varInfo.type !== VarType.any)+ draft.output_type = varInfo.type+ })+ onChange(newPayload)+ }, [onChange, payload])++ const handleListChange = useCallback((newList: ValueSelector[], changedItem?: ValueSelector) => {+ if (changedItem) {+ const chosenVariables = payload.variables+ if (chosenVariables.some(item => item.join('.') === (changedItem as ValueSelector).join('.')))+ return+ }++ const newPayload = produce(payload, (draft) => {+ draft.variables = newList+ if (newList.length === 0)+ draft.output_type = VarType.any+ })+ onChange(newPayload)+ }, [onChange, payload])++ const filterVar = useCallback((varPayload: Var) => {+ if (payload.output_type === VarType.any)+ return true+ return varPayload.type === payload.output_type+ }, [payload.output_type])++ const [isEditGroupName, {+ setTrue: setEditGroupName,+ setFalse: setNotEditGroupName,+ }] = useBoolean(false)++ const handleGroupNameChange = useCallback((e: ChangeEvent<any>) => {+ const value = e.target.value+ const { isValid, errorKey, errorMessageKey } = checkKeys([value], false)+ if (!isValid) {+ Toast.notify({+ type: 'error',+ message: t(`appDebug.varKeyError.${errorMessageKey}`, { key: errorKey }),+ })+ return+ }+ onGroupNameChange?.(value)+ }, [onGroupNameChange, t])++ return (+ <Field+ className='group'+ title={groupEnabled+ ? <div className='flex items-center'>+ <div className='flex items-center !normal-case'>+ <Folder className='mr-0.5 w-3.5 h-3.5' />+ {(!isEditGroupName)+ ? (+ <div className='flex items-center h-6 px-1 rounded-lg cursor-text hover:bg-gray-100' onClick={setEditGroupName}>+ {payload.group_name}+ </div>+ )+ : (+ <input+ type='text'+ className='h-6 px-1 rounded-lg bg-white border border-gray-300 focus:outline-none'+ // style={{+ // width: `${((payload.group_name?.length || 0) + 1) / 2}em`,+ // }}+ size={payload.group_name?.length} // to fit the input width+ autoFocus+ value={payload.group_name}+ onChange={handleGroupNameChange}+ onBlur={setNotEditGroupName}+ maxLength={30}+ />)}++ </div>+ {canRemove && (+ <div+ className='group-hover:block hidden ml-0.5 p-1 rounded-md text-gray-500 cursor-pointer hover:bg-[#FEE4E2] hover:text-[#D92D20]'+ onClick={onRemove}+ >+ <Trash03+ className='w-4 h-4'+ />+ </div>+ )}+ </div>+ : t(`${i18nPrefix}.title`)!}+ operations={+ <div className='flex items-center h-6 space-x-2'>+ {payload.variables.length > 0 && (+ <div className='flex items-center h-[18px] px-1 border border-black/8 rounded-[5px] text-xs font-medium text-gray-500 capitalize'>{payload.output_type}</div>+ )}+ {+ !readOnly+ ? <VarReferencePicker+ isAddBtnTrigger+ readonly={false}+ nodeId={nodeId}+ isShowNodeName+ value={[]}+ onChange={handleAddVariable}+ defaultVarKindType={VarKindType.variable}+ filterVar={filterVar}+ availableVars={availableVars}+ />+ : undefined+ }+ </div>+ }+ >+ <VarList+ readonly={readOnly}+ nodeId={nodeId}+ list={payload.variables}+ onChange={handleListChange}+ filterVar={filterVar}+ />+ </Field>+ )+}+export default React.memo(VarGroupItem)diff --git a/web/app/components/workflow/nodes/variable-assigner/components/var-list/index.tsx b/web/app/components/workflow/nodes/variable-assigner/components/var-list/index.tsxindex 36a34003fee..9afc4a0333c 100644--- a/web/app/components/workflow/nodes/variable-assigner/components/var-list/index.tsx+++ b/web/app/components/workflow/nodes/variable-assigner/components/var-list/index.tsx@@ -4,6 +4,7 @@ import { useTranslation } from 'react-i18next'import React, { useCallback } from 'react'import produce from 'immer'import RemoveButton from '../../../_base/components/remove-button'+import ListNoDataPlaceholder from '../../../_base/components/list-no-data-placeholder'import VarReferencePicker from '@/app/components/workflow/nodes/_base/components/variable/var-reference-picker'import type { ValueSelector, Var } from '@/app/components/workflow/types'import { VarType as VarKindType } from '@/app/components/workflow/nodes/tool/types'@@ -12,9 +13,8 @@ type Props = {readonly: booleannodeId: stringlist: ValueSelector[]- onChange: (list: ValueSelector[]) => void+ onChange: (list: ValueSelector[], value?: ValueSelector) => voidonOpen?: (index: number) => void- onlyLeafNodeVar?: booleanfilterVar?: (payload: Var, valueSelector: ValueSelector) => boolean}@@ -24,7 +24,6 @@ const VarList: FC<Props> = ({list,onChange,onOpen = () => { },- onlyLeafNodeVar,filterVar,}) => {const { t } = useTranslation()@@ -33,7 +32,7 @@ const VarList: FC<Props> = ({const newList = produce(list, (draft) => {draft[index] = value as ValueSelector})- onChange(newList)+ onChange(newList, value as ValueSelector)}}, [list, onChange])@@ -52,9 +51,9 @@ const VarList: FC<Props> = ({if (list.length === 0) {return (- <div className='flex rounded-md bg-gray-50 items-center h-[42px] justify-center leading-[18px] text-xs font-normal text-gray-500'>+ <ListNoDataPlaceholder>{t('workflow.nodes.variableAssigner.noVarTip')}- </div>+ </ListNoDataPlaceholder>)}@@ -70,7 +69,6 @@ const VarList: FC<Props> = ({value={item}onChange={handleVarReferenceChange(index)}onOpen={handleOpen(index)}- onlyLeafNodeVar={onlyLeafNodeVar}filterVar={filterVar}defaultVarKindType={VarKindType.variable}/>diff --git a/web/app/components/workflow/nodes/variable-assigner/components/var-list/use-var-list.ts b/web/app/components/workflow/nodes/variable-assigner/components/var-list/use-var-list.tsindex fcfb4b2e49c..5686f1a37a2 100644--- a/web/app/components/workflow/nodes/variable-assigner/components/var-list/use-var-list.ts+++ b/web/app/components/workflow/nodes/variable-assigner/components/var-list/use-var-list.ts@@ -2,7 +2,6 @@ import { useCallback } from 'react'import produce from 'immer'import type { VariableAssignerNodeType } from '../../types'import type { ValueSelector } from '@/app/components/workflow/types'-import { useEdgesInteractions } from '@/app/components/workflow/hooks'type Params = {id: string@@ -10,18 +9,15 @@ type Params = {setInputs: (newInputs: VariableAssignerNodeType) => void}function useVarList({- id,inputs,setInputs,}: Params) {- const { handleVariableAssignerEdgesChange } = useEdgesInteractions()const handleVarListChange = useCallback((newList: ValueSelector[]) => {const newInputs = produce(inputs, (draft) => {draft.variables = newList})setInputs(newInputs)- handleVariableAssignerEdgesChange(id, newList)- }, [inputs, setInputs, id, handleVariableAssignerEdgesChange])+ }, [inputs, setInputs])const handleAddVariable = useCallback(() => {const newInputs = produce(inputs, (draft) => {diff --git a/web/app/components/workflow/nodes/variable-assigner/default.ts b/web/app/components/workflow/nodes/variable-assigner/default.tsindex 7291f331c71..b30e64961d3 100644--- a/web/app/components/workflow/nodes/variable-assigner/default.ts+++ b/web/app/components/workflow/nodes/variable-assigner/default.ts@@ -7,14 +7,14 @@ const i18nPrefix = 'workflow'const nodeDefault: NodeDefault<VariableAssignerNodeType> = {defaultValue: {- output_type: VarType.string,+ output_type: VarType.any,variables: [],},getAvailablePrevNodes(isChatMode: boolean) {const nodes = isChatMode? ALL_CHAT_AVAILABLE_BLOCKS: ALL_COMPLETION_AVAILABLE_BLOCKS.filter(type => type !== BlockEnum.End)- return nodes.filter(type => type !== BlockEnum.IfElse && type !== BlockEnum.QuestionClassifier)+ return nodes},getAvailableNextNodes(isChatMode: boolean) {const nodes = isChatMode ? ALL_CHAT_AVAILABLE_BLOCKS : ALL_COMPLETION_AVAILABLE_BLOCKSdiff --git a/web/app/components/workflow/nodes/variable-assigner/hooks.ts b/web/app/components/workflow/nodes/variable-assigner/hooks.tsnew file mode 100644index 00000000000..c79f0ad6045--- /dev/null+++ b/web/app/components/workflow/nodes/variable-assigner/hooks.ts@@ -0,0 +1,243 @@+import { useCallback } from 'react'+import {+ useEdges,+ useNodes,+ useStoreApi,+} from 'reactflow'+import { useTranslation } from 'react-i18next'+import { uniqBy } from 'lodash-es'+import produce from 'immer'+import {+ useIsChatMode,+ useNodeDataUpdate,+ useWorkflow,+} from '../../hooks'+import { getNodesConnectedSourceOrTargetHandleIdsMap } from '../../utils'+import type {+ Edge,+ Node,+ ValueSelector,+ Var,+} from '../../types'+import { useWorkflowStore } from '../../store'+import type {+ VarGroupItem,+ VariableAssignerNodeType,+} from './types'+import { toNodeAvailableVars } from '@/app/components/workflow/nodes/_base/components/variable/utils'++export const useVariableAssigner = () => {+ const store = useStoreApi()+ const workflowStore = useWorkflowStore()+ const { handleNodeDataUpdate } = useNodeDataUpdate()++ const handleAssignVariableValueChange = useCallback((nodeId: string, value: ValueSelector, varDetail: Var, groupId?: string) => {+ const { getNodes } = store.getState()+ const nodes = getNodes()+ const node: Node<VariableAssignerNodeType> = nodes.find(node => node.id === nodeId)!++ let payload+ if (groupId && groupId !== 'target') {+ payload = {+ advanced_settings: {+ ...node.data.advanced_settings,+ groups: node.data.advanced_settings?.groups.map((group: VarGroupItem & { groupId: string }) => {+ if (group.groupId === groupId && !group.variables.some(item => item.join('.') === (value as ValueSelector).join('.'))) {+ return {+ ...group,+ variables: [...group.variables, value],+ output_type: varDetail.type,+ }+ }+ return group+ }),+ },+ }+ }+ else {+ if (node.data.variables.some(item => item.join('.') === (value as ValueSelector).join('.')))+ return+ payload = {+ variables: [...node.data.variables, value],+ output_type: varDetail.type,+ }+ }+ handleNodeDataUpdate({+ id: nodeId,+ data: payload,+ })+ }, [store, handleNodeDataUpdate])++ const handleAddVariableInAddVariablePopupWithPosition = useCallback((+ nodeId: string,+ variableAssignerNodeId: string,+ variableAssignerNodeHandleId: string,+ value: ValueSelector,+ varDetail: Var,+ ) => {+ const {+ getNodes,+ setNodes,+ } = store.getState()+ const {+ setShowAssignVariablePopup,+ } = workflowStore.getState()++ const newNodes = produce(getNodes(), (draft) => {+ draft.forEach((node) => {+ if (node.id === nodeId || node.id === variableAssignerNodeId) {+ node.data = {+ ...node.data,+ _showAddVariablePopup: false,+ _holdAddVariablePopup: false,+ }+ }+ })+ })+ setNodes(newNodes)+ setShowAssignVariablePopup(undefined)+ handleAssignVariableValueChange(variableAssignerNodeId, value, varDetail, variableAssignerNodeHandleId)+ }, [store, workflowStore, handleAssignVariableValueChange])++ const handleRemoveEdges = useCallback((nodeId: string, enabled: boolean) => {+ const {+ getNodes,+ setNodes,+ edges,+ setEdges,+ } = store.getState()+ const nodes = getNodes()+ const needDeleteEdges = edges.filter(edge => edge.target === nodeId)++ if (!needDeleteEdges.length)+ return++ const currentNode = nodes.find(node => node.id === nodeId)!+ const groups = currentNode.data.advanced_settings?.groups || []++ let shouldKeepEdges: Edge[] = []++ if (enabled) {+ shouldKeepEdges = edges.filter((edge) => {+ return edge.target === nodeId && edge.targetHandle === 'target'+ }).map((edge) => {+ return {+ ...edge,+ targetHandle: groups[0].groupId,+ }+ })+ }+ else {+ shouldKeepEdges = edges.filter((edge) => {+ return edge.target === nodeId && edge.targetHandle === groups[0].groupId+ }).map((edge) => {+ return {+ ...edge,+ targetHandle: 'target',+ }+ })+ }++ const nodesConnectedSourceOrTargetHandleIdsMap = getNodesConnectedSourceOrTargetHandleIdsMap(+ [+ ...needDeleteEdges.map((needDeleteEdge) => {+ return {+ type: 'remove',+ edge: needDeleteEdge,+ }+ }),+ ...shouldKeepEdges.map((shouldKeepEdge) => {+ return {+ type: 'add',+ edge: shouldKeepEdge,+ }+ }),+ ],+ nodes,+ )++ const newNodes = produce(nodes, (draft) => {+ draft.forEach((node) => {+ if (nodesConnectedSourceOrTargetHandleIdsMap[node.id]) {+ node.data = {+ ...node.data,+ ...nodesConnectedSourceOrTargetHandleIdsMap[node.id],+ }+ }+ })+ })+ setNodes(newNodes)+ const newEdges = produce(edges, (draft) => {+ draft = draft.filter(edge => edge.target !== nodeId)+ draft.push(...shouldKeepEdges)+ return draft+ })+ setEdges(newEdges)+ }, [store])++ const handleGroupItemMouseEnter = useCallback((groupId: string) => {+ const {+ setHoveringAssignVariableGroupId,+ } = workflowStore.getState()++ setHoveringAssignVariableGroupId(groupId)+ }, [workflowStore])++ const handleGroupItemMouseLeave = useCallback(() => {+ const {+ connectingNodePayload,+ setHoveringAssignVariableGroupId,+ } = workflowStore.getState()++ if (connectingNodePayload)+ setHoveringAssignVariableGroupId(undefined)+ }, [workflowStore])++ return {+ handleAddVariableInAddVariablePopupWithPosition,+ handleRemoveEdges,+ handleGroupItemMouseEnter,+ handleGroupItemMouseLeave,+ handleAssignVariableValueChange,+ }+}++export const useGetAvailableVars = () => {+ const { t } = useTranslation()+ const nodes: Node[] = useNodes()+ const edges: Edge[] = useEdges()+ const { getBeforeNodesInSameBranch } = useWorkflow()+ const isChatMode = useIsChatMode()+ const getAvailableVars = useCallback((nodeId: string, handleId: string, filterVar: (v: Var) => boolean) => {+ const availableNodes: Node[] = []+ const currentNode = nodes.find(node => node.id === nodeId)!++ if (!currentNode)+ return []+ const parentNode = nodes.find(node => node.id === currentNode.parentId)+ const connectedEdges = edges.filter(edge => edge.target === nodeId && edge.targetHandle === handleId)++ if (parentNode && !connectedEdges.length) {+ const beforeNodes = getBeforeNodesInSameBranch(parentNode.id)+ availableNodes.push(...beforeNodes)+ }+ else {+ connectedEdges.forEach((connectedEdge) => {+ const beforeNodes = getBeforeNodesInSameBranch(connectedEdge.source)+ const connectedNode = nodes.find(node => node.id === connectedEdge.source)!++ availableNodes.push(connectedNode, ...beforeNodes)+ })+ }++ return toNodeAvailableVars({+ parentNode,+ t,+ beforeNodes: uniqBy(availableNodes, 'id').filter(node => node.id !== nodeId),+ isChatMode,+ filterVar,+ })+ }, [nodes, edges, t, isChatMode, getBeforeNodesInSameBranch])++ return getAvailableVars+}diff --git a/web/app/components/workflow/nodes/variable-assigner/node.tsx b/web/app/components/workflow/nodes/variable-assigner/node.tsxindex f478cbd9adf..64e1485e503 100644--- a/web/app/components/workflow/nodes/variable-assigner/node.tsx+++ b/web/app/components/workflow/nodes/variable-assigner/node.tsx@@ -1,91 +1,61 @@import type { FC } from 'react'-import React from 'react'+import {+ memo,+ useMemo,+ useRef,+} from 'react'import type { NodeProps } from 'reactflow'import { useTranslation } from 'react-i18next'-import { NodeTargetHandle } from '../_base/components/node-handle'-import { BlockEnum } from '../../types'+import NodeGroupItem from './components/node-group-item'import type { VariableAssignerNodeType } from './types'-import { VarBlockIcon } from '@/app/components/workflow/block-icon'-import { Line3 } from '@/app/components/base/icons/src/public/common'-import { Variable02 } from '@/app/components/base/icons/src/vender/solid/development'-import {- useWorkflow,-} from '@/app/components/workflow/hooks'const i18nPrefix = 'workflow.nodes.variableAssigner'const Node: FC<NodeProps<VariableAssignerNodeType>> = (props) => {const { t } = useTranslation()+ const ref = useRef<HTMLDivElement>(null)const { id, data } = props- const { variables: originVariables, output_type } = data- const { getTreeLeafNodes } = useWorkflow()+ const { advanced_settings } = data- const availableNodes = getTreeLeafNodes(id)- const variables = originVariables.filter(item => item.length > 0)+ const groups = useMemo(() => {+ if (!advanced_settings?.group_enabled) {+ return [{+ groupEnabled: false,+ targetHandleId: 'target',+ title: t(`${i18nPrefix}.title`),+ type: data.output_type,+ variables: data.variables,+ variableAssignerNodeId: id,+ variableAssignerNodeData: data,+ }]+ }+ return advanced_settings.groups.map((group) => {+ return {+ groupEnabled: true,+ targetHandleId: group.groupId,+ title: group.group_name,+ type: group.output_type,+ variables: group.variables,+ variableAssignerNodeId: id,+ variableAssignerNodeData: data,+ }+ })+ }, [t, advanced_settings, data, id])return (- <div className='mb-1 px-3 py-1'>- <div className='mb-0.5 leading-4 text-xs font-medium text-gray-500 uppercase'>{t(`${i18nPrefix}.title`)}</div>+ <div className='relative mb-1 px-1' ref={ref}>{- variables.length === 0 && (- <div className='relative flex items-center h-6 justify-between bg-gray-100 rounded-md px-1 space-x-1 text-xs font-normal text-gray-400 uppercase'>- {t(`${i18nPrefix}.varNotSet`)}- <NodeTargetHandle- {...props}- handleId='varNotSet'- handleClassName='!top-1/2 !-translate-y-1/2 !-left-[21px]'+ groups.map((item) => {+ return (+ <NodeGroupItem+ key={item.title}+ item={item}/>- </div>- )- }- {variables.length > 0 && (- <>- <div className='space-y-0.5'>- {variables.map((item, index) => {- const node = availableNodes.find(node => node.id === item[0])- const varName = item[item.length - 1]-- return (- <div key={index} className='relative flex items-center h-6 bg-gray-100 rounded-md px-1 text-xs font-normal text-gray-700' >- <NodeTargetHandle- {...props}- handleId={item[0]}- handleClassName='!top-1/2 !-translate-y-1/2 !-left-[21px]'- />- <div className='flex items-center'>- <div className='p-[1px]'>- <VarBlockIcon- className='!text-gray-900'- type={(node?.data.type as BlockEnum) || BlockEnum.Start}- />- </div>- <div className='max-w-[85px] truncate mx-0.5 text-xs font-medium text-gray-700' title={node?.data.title}>{node?.data.title}</div>- <Line3 className='mr-0.5'></Line3>- </div>- <div className='flex items-center text-primary-600'>- <Variable02 className='w-3.5 h-3.5' />- <div className='max-w-[75px] truncate ml-0.5 text-xs font-medium' title={varName}>{varName}</div>- </div>- {/* <div className='ml-0.5 text-xs font-normal text-gray-500'>{output_type}</div> */}- </div>- )- },-- )}- </div>- <div className='mt-2 flex items-center h-6 justify-between bg-gray-100 rounded-md px-1 space-x-1 text-xs font-normal text-gray-700'>- <div className='text-xs font-medium text-gray-500 uppercase'>- {t(`${i18nPrefix}.outputType`)}- </div>- <div className='text-xs font-normal text-gray-700'>- {t(`${i18nPrefix}.type.${output_type}`)}- </div>- </div>- </>- )+ )+ })}</div >)}-export default React.memo(Node)+export default memo(Node)diff --git a/web/app/components/workflow/nodes/variable-assigner/panel.tsx b/web/app/components/workflow/nodes/variable-assigner/panel.tsxindex a1236c84f04..36262416432 100644--- a/web/app/components/workflow/nodes/variable-assigner/panel.tsx+++ b/web/app/components/workflow/nodes/variable-assigner/panel.tsx@@ -1,17 +1,17 @@import type { FC } from 'react'import React from 'react'import { useTranslation } from 'react-i18next'+// import cn from 'classnames'+// import Field from '../_base/components/field'+import RemoveEffectVarConfirm from '../_base/components/remove-effect-var-confirm'import useConfig from './use-config'-import VarList from './components/var-list'import type { VariableAssignerNodeType } from './types'-import Field from '@/app/components/workflow/nodes/_base/components/field'-import Selector from '@/app/components/workflow/nodes/_base/components/selector'-import AddButton from '@/app/components/base/button/add-button'-import { ChevronDown } from '@/app/components/base/icons/src/vender/line/arrows'-import type { NodePanelProps } from '@/app/components/workflow/types'-import { VarType } from '@/app/components/workflow/types'+import VarGroupItem from './components/var-group-item'+import { type NodePanelProps } from '@/app/components/workflow/types'import Split from '@/app/components/workflow/nodes/_base/components/split'-import OutputVars, { VarItem } from '@/app/components/workflow/nodes/_base/components/output-vars'+// import OutputVars, { VarItem } from '@/app/components/workflow/nodes/_base/components/output-vars'+// import Switch from '@/app/components/base/switch'+import AddButton from '@/app/components/workflow/nodes/_base/components/add-button'const i18nPrefix = 'workflow.nodes.variableAssigner'const Panel: FC<NodePanelProps<VariableAssignerNodeType>> = ({@@ -23,70 +23,105 @@ const Panel: FC<NodePanelProps<VariableAssignerNodeType>> = ({const {readOnly,inputs,- handleOutputTypeChange,- handleVarListChange,- handleAddVariable,- handleOnVarOpen,+ handleListOrTypeChange,+ isEnableGroup,+ // handleGroupEnabledChange,+ handleAddGroup,+ handleListOrTypeChangeInGroup,+ handleGroupRemoved,+ handleVarGroupNameChange,+ isShowRemoveVarConfirm,+ hideRemoveVarConfirm,+ onRemoveVarConfirm,+ getAvailableVars,filterVar,} = useConfig(id, data)- const typeOptions = [- { label: t(`${i18nPrefix}.type.string`), value: VarType.string },- { label: t(`${i18nPrefix}.type.number`), value: VarType.number },- { label: t(`${i18nPrefix}.type.object`), value: VarType.object },- { label: t(`${i18nPrefix}.type.array`), value: VarType.array },- ]-return (<div className='mt-2'><div className='px-4 pb-4 space-y-4'>+ {!isEnableGroup+ ? (+ <VarGroupItem+ readOnly={readOnly}+ nodeId={id}+ payload={{+ output_type: inputs.output_type,+ variables: inputs.variables,+ }}+ onChange={handleListOrTypeChange}+ groupEnabled={false}+ availableVars={getAvailableVars(id, 'target', filterVar(inputs.output_type))}+ />+ )+ : (<div>+ <div className='space-y-2'>+ {inputs.advanced_settings?.groups.map((item, index) => (+ <div key={item.groupId}>+ <VarGroupItem+ readOnly={readOnly}+ nodeId={id}+ payload={item}+ onChange={handleListOrTypeChangeInGroup(item.groupId)}+ groupEnabled+ canRemove={!readOnly && inputs.advanced_settings?.groups.length > 1}+ onRemove={handleGroupRemoved(item.groupId)}+ onGroupNameChange={handleVarGroupNameChange(item.groupId)}+ availableVars={getAvailableVars(id, item.groupId, filterVar(item.output_type))}+ />+ {index !== inputs.advanced_settings?.groups.length - 1 && <Split className='my-4' />}+ </div>++ ))}+ </div>+ <AddButton+ className='mt-2'+ text={t(`${i18nPrefix}.addGroup`)}+ onClick={handleAddGroup}+ />+ </div>)}+ </div>+ {/* <Split /> */}+ {/* <div className={cn('px-4 pt-4', isEnableGroup ? 'pb-4' : 'pb-2')}><Field- title={t(`${i18nPrefix}.outputVarType`)}- >- <Selector- readonly={readOnly}- value={inputs.output_type}- options={typeOptions}- onChange={handleOutputTypeChange}- trigger={- <div className='flex items-center h-8 justify-between px-2.5 rounded-lg bg-gray-100 capitalize'>- <div className='text-[13px] font-normal text-gray-900'>{inputs.output_type}</div>- {!readOnly && <ChevronDown className='w-3.5 h-3.5 text-gray-700' />}- </div>- }- popupClassName='!top-[36px] !w-[387px]'- showChecked- />- </Field>- <Field- title={t(`${i18nPrefix}.title`)}+ title={t(`${i18nPrefix}.aggregationGroup`)}+ tooltip={t(`${i18nPrefix}.aggregationGroupTip`)!}operations={- !readOnly ? <AddButton onClick={handleAddVariable} /> : undefined- }- >- <VarList- readonly={readOnly}- nodeId={id}- list={inputs.variables}- onChange={handleVarListChange}- onOpen={handleOnVarOpen}- onlyLeafNodeVar- filterVar={filterVar}- />- </Field>- </div>- <Split />- <div className='px-4 pt-4 pb-2'>- <OutputVars>- <>- <VarItem- name='output'- type={inputs.output_type}- description={t(`${i18nPrefix}.outputVars.output`)}+ <Switch+ defaultValue={isEnableGroup}+ onChange={handleGroupEnabledChange}+ size='md'+ disabled={readOnly}/>- </>- </OutputVars>- </div>+ }+ />+ </div> */}+ {/* {isEnableGroup && (+ <>+ <Split />+ <div className='px-4 pt-4 pb-2'>+ <OutputVars>+ <>+ {inputs.advanced_settings?.groups.map((item, index) => (+ <VarItem+ key={index}+ name={`${item.group_name}.output`}+ type={item.output_type}+ description={t(`${i18nPrefix}.outputVars.varDescribe`, {+ groupName: item.group_name,+ })}+ />+ ))}+ </>+ </OutputVars>+ </div>+ </>+ )} */}+ <RemoveEffectVarConfirm+ isShow={isShowRemoveVarConfirm}+ onCancel={hideRemoveVarConfirm}+ onConfirm={onRemoveVarConfirm}+ /></div>)}diff --git a/web/app/components/workflow/nodes/variable-assigner/types.ts b/web/app/components/workflow/nodes/variable-assigner/types.tsindex 8a923f02909..0bfc6f56a09 100644--- a/web/app/components/workflow/nodes/variable-assigner/types.ts+++ b/web/app/components/workflow/nodes/variable-assigner/types.ts@@ -1,6 +1,15 @@import type { CommonNodeType, ValueSelector, VarType } from '@/app/components/workflow/types'-export type VariableAssignerNodeType = CommonNodeType & {+export type VarGroupItem = {output_type: VarTypevariables: ValueSelector[]}+export type VariableAssignerNodeType = CommonNodeType & VarGroupItem & {+ advanced_settings: {+ group_enabled: boolean+ groups: ({+ group_name: string+ groupId: string+ } & VarGroupItem)[]+ }+}diff --git a/web/app/components/workflow/nodes/variable-assigner/use-config.ts b/web/app/components/workflow/nodes/variable-assigner/use-config.tsindex 2bbe2ab12f2..11418080679 100644--- a/web/app/components/workflow/nodes/variable-assigner/use-config.ts+++ b/web/app/components/workflow/nodes/variable-assigner/use-config.ts@@ -1,10 +1,13 @@-import { useCallback, useEffect, useState } from 'react'+import { useCallback, useState } from 'react'import produce from 'immer'-import useVarList from './components/var-list/use-var-list'-import type { VariableAssignerNodeType } from './types'+import { useBoolean } from 'ahooks'+import { v4 as uuid4 } from 'uuid'+import type { ValueSelector, Var } from '../../types'+import { VarType } from '../../types'+import type { VarGroupItem, VariableAssignerNodeType } from './types'+import { useGetAvailableVars, useVariableAssigner } from './hooks'import useNodeCrud from '@/app/components/workflow/nodes/_base/hooks/use-node-crud'-import type { ValueSelector, Var } from '@/app/components/workflow/types'-import { BlockEnum, VarType } from '@/app/components/workflow/types'+import {useNodesReadOnly,useWorkflow,@@ -12,68 +15,176 @@ import {const useConfig = (id: string, payload: VariableAssignerNodeType) => {const { nodesReadOnly: readOnly } = useNodesReadOnly()+ const { handleOutVarRenameChange, isVarUsedInNodes, removeUsedVarInNodes } = useWorkflow()+const { inputs, setInputs } = useNodeCrud<VariableAssignerNodeType>(id, payload)- const { getBeforeNodeById } = useWorkflow()- const beforeNodes = getBeforeNodeById(id)+ const isEnableGroup = !!inputs.advanced_settings?.group_enabled+ const { handleRemoveEdges } = useVariableAssigner()++ // Not Enable Group+ const handleListOrTypeChange = useCallback((payload: VarGroupItem) => {+ setInputs({+ ...inputs,+ ...payload,+ })+ }, [inputs, setInputs])- useEffect(() => {- if (beforeNodes.length !== 1 || inputs.variables.length > 0)- return- const beforeNode = beforeNodes[0]- if (beforeNode.data.type === BlockEnum.KnowledgeRetrieval) {- const newInputs = produce(inputs, (draft: VariableAssignerNodeType) => {- draft.output_type = VarType.array- draft.variables[0] = [beforeNode.id, 'result']+ const handleListOrTypeChangeInGroup = useCallback((groupId: string) => {+ return (payload: VarGroupItem) => {+ const index = inputs.advanced_settings.groups.findIndex(item => item.groupId === groupId)+ const newInputs = produce(inputs, (draft) => {+ draft.advanced_settings.groups[index] = {+ ...draft.advanced_settings.groups[index],+ ...payload,+ }})setInputs(newInputs)}- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [beforeNodes, inputs.variables])-- const handleOutputTypeChange = useCallback((outputType: string) => {- const newInputs = produce(inputs, (draft: VariableAssignerNodeType) => {- draft.output_type = outputType as VarType- })- setInputs(newInputs)}, [inputs, setInputs])- const { handleVarListChange, handleAddVariable } = useVarList({- id,- inputs,- setInputs,- })+ const getAvailableVars = useGetAvailableVars()+ const filterVar = (varType: VarType) => {+ return (v: Var) => {+ if (varType === VarType.any)+ return true+ if (v.type === VarType.any)+ return true+ return v.type === varType+ }+ }++ const [isShowRemoveVarConfirm, {+ setTrue: showRemoveVarConfirm,+ setFalse: hideRemoveVarConfirm,+ }] = useBoolean(false)++ const [removedVars, setRemovedVars] = useState<ValueSelector[]>([])+ const [removeType, setRemoveType] = useState<'group' | 'enableChanged'>('group')+ const [removedGroupIndex, setRemovedGroupIndex] = useState<number>(-1)+ const handleGroupRemoved = useCallback((groupId: string) => {+ return () => {+ const index = inputs.advanced_settings.groups.findIndex(item => item.groupId === groupId)+ if (isVarUsedInNodes([id, inputs.advanced_settings.groups[index].group_name, 'output'])) {+ showRemoveVarConfirm()+ setRemovedVars([[id, inputs.advanced_settings.groups[index].group_name, 'output']])+ setRemoveType('group')+ setRemovedGroupIndex(index)+ return+ }+ const newInputs = produce(inputs, (draft) => {+ draft.advanced_settings.groups.splice(index, 1)+ })+ setInputs(newInputs)+ }+ }, [id, inputs, isVarUsedInNodes, setInputs, showRemoveVarConfirm])++ const handleGroupEnabledChange = useCallback((enabled: boolean) => {+ const newInputs = produce(inputs, (draft) => {+ if (!draft.advanced_settings)+ draft.advanced_settings = { group_enabled: false, groups: [] }+ if (enabled) {+ if (draft.advanced_settings.groups.length === 0) {+ const DEFAULT_GROUP_NAME = 'Group1'+ draft.advanced_settings.groups = [{+ output_type: draft.output_type,+ variables: draft.variables,+ group_name: DEFAULT_GROUP_NAME,+ groupId: uuid4(),+ }]- const { variables } = inputs- const [currVarIndex, setCurrVarIndex] = useState(-1)- const currVar = variables[currVarIndex]- const handleOnVarOpen = useCallback((index: number) => {- setCurrVarIndex(index)- }, [])- const filterVar = useCallback((varPayload: Var, valueSelector: ValueSelector) => {- const type = varPayload.type- if ((inputs.output_type !== VarType.array && type !== inputs.output_type) || (- inputs.output_type === VarType.array && ![VarType.array, VarType.arrayString, VarType.arrayNumber, VarType.arrayObject].includes(type)- ))- return false+ handleOutVarRenameChange(id, [id, 'output'], [id, DEFAULT_GROUP_NAME, 'output'])+ }+ }+ else {+ if (draft.advanced_settings.groups.length > 0) {+ if (draft.advanced_settings.groups.length > 1) {+ const useVars = draft.advanced_settings.groups.filter((item, index) => index > 0 && isVarUsedInNodes([id, item.group_name, 'output']))+ if (useVars.length > 0) {+ showRemoveVarConfirm()+ setRemovedVars(useVars.map(item => [id, item.group_name, 'output']))+ setRemoveType('enableChanged')+ return+ }+ }+ draft.output_type = draft.advanced_settings.groups[0].output_type+ draft.variables = draft.advanced_settings.groups[0].variables+ handleOutVarRenameChange(id, [id, draft.advanced_settings.groups[0].group_name, 'output'], [id, 'output'])+ }+ }+ draft.advanced_settings.group_enabled = enabled+ })+ setInputs(newInputs)+ handleRemoveEdges(id, enabled)+ }, [handleOutVarRenameChange, id, inputs, isVarUsedInNodes, setInputs, showRemoveVarConfirm, handleRemoveEdges])- // can not choose the same node- if (!currVar)- return true+ const handleAddGroup = useCallback(() => {+ let maxInGroupName = 1+ inputs.advanced_settings.groups.forEach((item) => {+ const match = item.group_name.match(/(\d+)$/)+ if (match) {+ const num = parseInt(match[1], 10)+ if (num > maxInGroupName)+ maxInGroupName = num+ }+ })+ const newInputs = produce(inputs, (draft) => {+ draft.advanced_settings.groups.push({+ output_type: VarType.any,+ variables: [],+ group_name: `Group${maxInGroupName + 1}`,+ groupId: uuid4(),+ })+ })+ setInputs(newInputs)+ }, [inputs, setInputs])- const selectNodeId = valueSelector[0]+ const handleVarGroupNameChange = useCallback((groupId: string) => {+ return (name: string) => {+ const index = inputs.advanced_settings.groups.findIndex(item => item.groupId === groupId)+ const newInputs = produce(inputs, (draft) => {+ draft.advanced_settings.groups[index].group_name = name+ })+ handleOutVarRenameChange(id, [id, inputs.advanced_settings.groups[index].group_name, 'output'], [id, name, 'output'])+ setInputs(newInputs)+ }+ }, [handleOutVarRenameChange, id, inputs, setInputs])- if (selectNodeId !== currVar[0] && variables.find(v => v[0] === selectNodeId))- return false+ const onRemoveVarConfirm = useCallback(() => {+ removedVars.forEach((v) => {+ removeUsedVarInNodes(v)+ })+ hideRemoveVarConfirm()+ if (removeType === 'group') {+ const newInputs = produce(inputs, (draft) => {+ draft.advanced_settings.groups.splice(removedGroupIndex, 1)+ })+ setInputs(newInputs)+ }+ else {+ // removeType === 'enableChanged' to enabled+ const newInputs = produce(inputs, (draft) => {+ draft.advanced_settings.group_enabled = false+ draft.output_type = draft.advanced_settings.groups[0].output_type+ draft.variables = draft.advanced_settings.groups[0].variables+ })+ setInputs(newInputs)+ }+ }, [removedVars, hideRemoveVarConfirm, removeType, removeUsedVarInNodes, inputs, setInputs, removedGroupIndex])- return true- }, [currVar, inputs.output_type, variables])return {readOnly,inputs,- handleOutputTypeChange,- handleVarListChange,- handleAddVariable,- handleOnVarOpen,+ handleListOrTypeChange,+ isEnableGroup,+ handleGroupEnabledChange,+ handleAddGroup,+ handleListOrTypeChangeInGroup,+ handleGroupRemoved,+ handleVarGroupNameChange,+ isShowRemoveVarConfirm,+ hideRemoveVarConfirm,+ onRemoveVarConfirm,+ getAvailableVars,filterVar,}}diff --git a/web/app/components/workflow/nodes/variable-assigner/utils.ts b/web/app/components/workflow/nodes/variable-assigner/utils.tsindex c8290f67111..a41acf93f53 100644--- a/web/app/components/workflow/nodes/variable-assigner/utils.ts+++ b/web/app/components/workflow/nodes/variable-assigner/utils.ts@@ -1,5 +1,16 @@-import type { VariableAssignerNodeType } from './types'+import type { Var } from '../../types'+import { VarType } from '../../types'-export const checkNodeValid = (payload: VariableAssignerNodeType) => {+export const checkNodeValid = () => {return true}++export const filterVar = (varType: VarType) => {+ return (v: Var) => {+ if (varType === VarType.any)+ return true+ if (v.type === VarType.any)+ return true+ return v.type === varType+ }+}diff --git a/web/app/components/workflow/panel/debug-and-preview/hooks.ts b/web/app/components/workflow/panel/debug-and-preview/hooks.tsindex 1c143a2b01e..d7f6ee48281 100644--- a/web/app/components/workflow/panel/debug-and-preview/hooks.ts+++ b/web/app/components/workflow/panel/debug-and-preview/hooks.ts@@ -180,6 +180,8 @@ export const useChat = (isAnswer: true,}+ let isInIteration = false+handleResponding(true)const bodyParams = {@@ -297,10 +299,11 @@ export const useChat = (}}))},- onNodeStarted: ({ data }) => {+ onIterationStart: ({ data }) => {responseItem.workflowProcess!.tracing!.push({...data,status: NodeRunningStatus.Running,+ details: [],} as any)handleUpdateChatList(produce(chatListRef.current, (draft) => {const currentIndex = draft.findIndex(item => item.id === responseItem.id)@@ -309,22 +312,91 @@ export const useChat = (...responseItem,}}))+ isInIteration = true},- onNodeFinished: ({ data }) => {- const currentIndex = responseItem.workflowProcess!.tracing!.findIndex(item => item.node_id === data.node_id)- responseItem.workflowProcess!.tracing[currentIndex] = {- ...(responseItem.workflowProcess!.tracing[currentIndex].extras- ? { extras: responseItem.workflowProcess!.tracing[currentIndex].extras }- : {}),+ onIterationNext: () => {+ const tracing = responseItem.workflowProcess!.tracing!+ const iterations = tracing[tracing.length - 1]+ iterations.details!.push([])++ handleUpdateChatList(produce(chatListRef.current, (draft) => {+ const currentIndex = draft.length - 1+ draft[currentIndex] = responseItem+ }))+ },+ onIterationFinish: ({ data }) => {+ const tracing = responseItem.workflowProcess!.tracing!+ const iterations = tracing[tracing.length - 1]+ tracing[tracing.length - 1] = {+ ...iterations,...data,+ status: NodeRunningStatus.Succeeded,} as anyhandleUpdateChatList(produce(chatListRef.current, (draft) => {- const currentIndex = draft.findIndex(item => item.id === responseItem.id)- draft[currentIndex] = {- ...draft[currentIndex],- ...responseItem,- }+ const currentIndex = draft.length - 1+ draft[currentIndex] = responseItem}))++ isInIteration = false+ },+ onNodeStarted: ({ data }) => {+ if (isInIteration) {+ const tracing = responseItem.workflowProcess!.tracing!+ const iterations = tracing[tracing.length - 1]+ const currIteration = iterations.details![iterations.details!.length - 1]+ currIteration.push({+ ...data,+ status: NodeRunningStatus.Running,+ } as any)+ handleUpdateChatList(produce(chatListRef.current, (draft) => {+ const currentIndex = draft.length - 1+ draft[currentIndex] = responseItem+ }))+ }+ else {+ responseItem.workflowProcess!.tracing!.push({+ ...data,+ status: NodeRunningStatus.Running,+ } as any)+ handleUpdateChatList(produce(chatListRef.current, (draft) => {+ const currentIndex = draft.findIndex(item => item.id === responseItem.id)+ draft[currentIndex] = {+ ...draft[currentIndex],+ ...responseItem,+ }+ }))+ }+ },+ onNodeFinished: ({ data }) => {+ if (isInIteration) {+ const tracing = responseItem.workflowProcess!.tracing!+ const iterations = tracing[tracing.length - 1]+ const currIteration = iterations.details![iterations.details!.length - 1]+ currIteration[currIteration.length - 1] = {+ ...data,+ status: NodeRunningStatus.Succeeded,+ } as any+ handleUpdateChatList(produce(chatListRef.current, (draft) => {+ const currentIndex = draft.length - 1+ draft[currentIndex] = responseItem+ }))+ }+ else {+ const currentIndex = responseItem.workflowProcess!.tracing!.findIndex(item => item.node_id === data.node_id)+ responseItem.workflowProcess!.tracing[currentIndex] = {+ ...(responseItem.workflowProcess!.tracing[currentIndex].extras+ ? { extras: responseItem.workflowProcess!.tracing[currentIndex].extras }+ : {}),+ ...data,+ } as any+ handleUpdateChatList(produce(chatListRef.current, (draft) => {+ const currentIndex = draft.findIndex(item => item.id === responseItem.id)+ draft[currentIndex] = {+ ...draft[currentIndex],+ ...responseItem,+ }+ }))+ }},},)diff --git a/web/app/components/workflow/panel/index.tsx b/web/app/components/workflow/panel/index.tsxindex 6614362c37f..e5d8aa4e208 100644--- a/web/app/components/workflow/panel/index.tsx+++ b/web/app/components/workflow/panel/index.tsx@@ -28,11 +28,12 @@ const Panel: FC = () => {enableShortcuts,disableShortcuts,} = useWorkflow()- const { currentLogItem, setCurrentLogItem, showMessageLogModal, setShowMessageLogModal } = useAppStore(useShallow(state => ({+ const { currentLogItem, setCurrentLogItem, showMessageLogModal, setShowMessageLogModal, currentLogModalActiveTab } = useAppStore(useShallow(state => ({currentLogItem: state.currentLogItem,setCurrentLogItem: state.setCurrentLogItem,showMessageLogModal: state.showMessageLogModal,setShowMessageLogModal: state.setShowMessageLogModal,+ currentLogModalActiveTab: state.currentLogModalActiveTab,})))return (@@ -55,6 +56,7 @@ const Panel: FC = () => {setCurrentLogItem()setShowMessageLogModal(false)}}+ defaultTab={currentLogModalActiveTab}/>)}diff --git a/web/app/components/workflow/panel/inputs-panel.tsx b/web/app/components/workflow/panel/inputs-panel.tsxindex 9a1241e0b9a..cce27ae0384 100644--- a/web/app/components/workflow/panel/inputs-panel.tsx+++ b/web/app/components/workflow/panel/inputs-panel.tsx@@ -46,7 +46,7 @@ const InputsPanel = ({ onRun }: Props) => {{type: InputVarType.files,variable: '__image',- required: true,+ required: false,label: 'files',},]diff --git a/web/app/components/workflow/panel/workflow-preview.tsx b/web/app/components/workflow/panel/workflow-preview.tsxindex f0434db46f7..73bc895b734 100644--- a/web/app/components/workflow/panel/workflow-preview.tsx+++ b/web/app/components/workflow/panel/workflow-preview.tsx@@ -1,5 +1,6 @@import {memo,+ useCallback,useEffect,// useRef,useState,@@ -7,6 +8,7 @@ import {import cn from 'classnames'import { useTranslation } from 'react-i18next'import copy from 'copy-to-clipboard'+import { useBoolean } from 'ahooks'import ResultText from '../run/result-text'import ResultPanel from '../run/result-panel'import TracingPanel from '../run/tracing-panel'@@ -19,12 +21,18 @@ import {} from '../types'import { SimpleBtn } from '../../app/text-generate/item'import Toast from '../../base/toast'+import IterationResultPanel from '../run/iteration-result-panel'import InputsPanel from './inputs-panel'import Loading from '@/app/components/base/loading'import { XClose } from '@/app/components/base/icons/src/vender/line/general'import { Clipboard } from '@/app/components/base/icons/src/vender/line/files'+import type { NodeTracing } from '@/types/workflow'-const WorkflowPreview = () => {+const WorkflowPreview = ({+ onShowIterationDetail,+}: {+ onShowIterationDetail: (detail: NodeTracing[][]) => void+}) => {const { t } = useTranslation()const { handleCancelDebugAndPreviewPanel } = useWorkflowInteractions()const workflowRunningData = useStore(s => s.workflowRunningData)@@ -46,6 +54,31 @@ const WorkflowPreview = () => {switchTab('DETAIL')}, [workflowRunningData])+ const [iterationRunResult, setIterationRunResult] = useState<NodeTracing[][]>([])+ const [isShowIterationDetail, {+ setTrue: doShowIterationDetail,+ setFalse: doHideIterationDetail,+ }] = useBoolean(false)++ const handleShowIterationDetail = useCallback((detail: NodeTracing[][]) => {+ setIterationRunResult(detail)+ doShowIterationDetail()+ }, [doShowIterationDetail])++ if (isShowIterationDetail) {+ return (+ <div className={`+ flex flex-col w-[420px] h-full rounded-l-2xl border-[0.5px] border-gray-200 shadow-xl bg-white+ `}>+ <IterationResultPanel+ list={iterationRunResult}+ onHide={doHideIterationDetail}+ onBack={doHideIterationDetail}+ />+ </div>+ )+ }+return (<div className={`flex flex-col w-[420px] h-full rounded-l-2xl border-[0.5px] border-gray-200 shadow-xl bg-white@@ -57,115 +90,129 @@ const WorkflowPreview = () => {</div></div><div className='grow relative flex flex-col'>- <div className='shrink-0 flex items-center px-4 border-b-[0.5px] border-[rgba(0,0,0,0.05)]'>- {showInputsPanel && (- <div- className={cn(- 'mr-6 py-3 border-b-2 border-transparent text-[13px] font-semibold leading-[18px] text-gray-400 cursor-pointer',- currentTab === 'INPUT' && '!border-[rgb(21,94,239)] text-gray-700',- )}- onClick={() => switchTab('INPUT')}- >{t('runLog.input')}</div>- )}- <div- className={cn(- 'mr-6 py-3 border-b-2 border-transparent text-[13px] font-semibold leading-[18px] text-gray-400 cursor-pointer',- currentTab === 'RESULT' && '!border-[rgb(21,94,239)] text-gray-700',- !workflowRunningData && 'opacity-30 !cursor-not-allowed',- )}- onClick={() => {- if (!workflowRunningData)- return- switchTab('RESULT')- }}- >{t('runLog.result')}</div>- <div- className={cn(- 'mr-6 py-3 border-b-2 border-transparent text-[13px] font-semibold leading-[18px] text-gray-400 cursor-pointer',- currentTab === 'DETAIL' && '!border-[rgb(21,94,239)] text-gray-700',- !workflowRunningData && 'opacity-30 !cursor-not-allowed',- )}- onClick={() => {- if (!workflowRunningData)- return- switchTab('DETAIL')- }}- >{t('runLog.detail')}</div>- <div- className={cn(- 'mr-6 py-3 border-b-2 border-transparent text-[13px] font-semibold leading-[18px] text-gray-400 cursor-pointer',- currentTab === 'TRACING' && '!border-[rgb(21,94,239)] text-gray-700',- !workflowRunningData && 'opacity-30 !cursor-not-allowed',- )}- onClick={() => {- if (!workflowRunningData)- return- switchTab('TRACING')- }}- >{t('runLog.tracing')}</div>- </div>- <div className={cn(- 'grow bg-white h-0 overflow-y-auto rounded-b-2xl',- (currentTab === 'RESULT' || currentTab === 'TRACING') && '!bg-gray-50',- )}>- {currentTab === 'INPUT' && showInputsPanel && (- <InputsPanel onRun={() => switchTab('RESULT')} />- )}- {currentTab === 'RESULT' && (+ {isShowIterationDetail+ ? (+ <IterationResultPanel+ list={iterationRunResult}+ onHide={doHideIterationDetail}+ onBack={doHideIterationDetail}+ />+ )+ : (<>- <ResultText- isRunning={workflowRunningData?.result?.status === WorkflowRunningStatus.Running || !workflowRunningData?.result}- outputs={workflowRunningData?.resultText}- error={workflowRunningData?.result?.error}- onClick={() => switchTab('DETAIL')}- />- {(workflowRunningData?.result.status !== WorkflowRunningStatus.Succeeded || !workflowRunningData?.resultText) && (- <SimpleBtn- className={cn('ml-4 mb-4 inline-flex space-x-1')}+ <div className='shrink-0 flex items-center px-4 border-b-[0.5px] border-[rgba(0,0,0,0.05)]'>+ {showInputsPanel && (+ <div+ className={cn(+ 'mr-6 py-3 border-b-2 border-transparent text-[13px] font-semibold leading-[18px] text-gray-400 cursor-pointer',+ currentTab === 'INPUT' && '!border-[rgb(21,94,239)] text-gray-700',+ )}+ onClick={() => switchTab('INPUT')}+ >{t('runLog.input')}</div>+ )}+ <div+ className={cn(+ 'mr-6 py-3 border-b-2 border-transparent text-[13px] font-semibold leading-[18px] text-gray-400 cursor-pointer',+ currentTab === 'RESULT' && '!border-[rgb(21,94,239)] text-gray-700',+ !workflowRunningData && 'opacity-30 !cursor-not-allowed',+ )}onClick={() => {- const content = workflowRunningData?.resultText- if (typeof content === 'string')- copy(content)- else- copy(JSON.stringify(content))- Toast.notify({ type: 'success', message: t('common.actionMsg.copySuccessfully') })- }}>- <Clipboard className='w-3.5 h-3.5' />- <div>{t('common.operation.copy')}</div>- </SimpleBtn>- )}+ if (!workflowRunningData)+ return+ switchTab('RESULT')+ }}+ >{t('runLog.result')}</div>+ <div+ className={cn(+ 'mr-6 py-3 border-b-2 border-transparent text-[13px] font-semibold leading-[18px] text-gray-400 cursor-pointer',+ currentTab === 'DETAIL' && '!border-[rgb(21,94,239)] text-gray-700',+ !workflowRunningData && 'opacity-30 !cursor-not-allowed',+ )}+ onClick={() => {+ if (!workflowRunningData)+ return+ switchTab('DETAIL')+ }}+ >{t('runLog.detail')}</div>+ <div+ className={cn(+ 'mr-6 py-3 border-b-2 border-transparent text-[13px] font-semibold leading-[18px] text-gray-400 cursor-pointer',+ currentTab === 'TRACING' && '!border-[rgb(21,94,239)] text-gray-700',+ !workflowRunningData && 'opacity-30 !cursor-not-allowed',+ )}+ onClick={() => {+ if (!workflowRunningData)+ return+ switchTab('TRACING')+ }}+ >{t('runLog.tracing')}</div>+ </div>+ <div className={cn(+ 'grow bg-white h-0 overflow-y-auto rounded-b-2xl',+ (currentTab === 'RESULT' || currentTab === 'TRACING') && '!bg-gray-50',+ )}>+ {currentTab === 'INPUT' && showInputsPanel && (+ <InputsPanel onRun={() => switchTab('RESULT')} />+ )}+ {currentTab === 'RESULT' && (+ <>+ <ResultText+ isRunning={workflowRunningData?.result?.status === WorkflowRunningStatus.Running || !workflowRunningData?.result}+ outputs={workflowRunningData?.resultText}+ error={workflowRunningData?.result?.error}+ onClick={() => switchTab('DETAIL')}+ />+ {(workflowRunningData?.result.status === WorkflowRunningStatus.Succeeded && workflowRunningData?.resultText && typeof workflowRunningData?.resultText === 'string') && (+ <SimpleBtn+ className={cn('ml-4 mb-4 inline-flex space-x-1')}+ onClick={() => {+ const content = workflowRunningData?.resultText+ if (typeof content === 'string')+ copy(content)+ else+ copy(JSON.stringify(content))+ Toast.notify({ type: 'success', message: t('common.actionMsg.copySuccessfully') })+ }}>+ <Clipboard className='w-3.5 h-3.5' />+ <div>{t('common.operation.copy')}</div>+ </SimpleBtn>+ )}+ </>+ )}+ {currentTab === 'DETAIL' && (+ <ResultPanel+ inputs={workflowRunningData?.result?.inputs}+ outputs={workflowRunningData?.result?.outputs}+ status={workflowRunningData?.result?.status || ''}+ error={workflowRunningData?.result?.error}+ elapsed_time={workflowRunningData?.result?.elapsed_time}+ total_tokens={workflowRunningData?.result?.total_tokens}+ created_at={workflowRunningData?.result?.created_at}+ created_by={(workflowRunningData?.result?.created_by as any)?.name}+ steps={workflowRunningData?.result?.total_steps}+ />+ )}+ {currentTab === 'DETAIL' && !workflowRunningData?.result && (+ <div className='flex h-full items-center justify-center bg-white'>+ <Loading />+ </div>+ )}+ {currentTab === 'TRACING' && (+ <TracingPanel+ list={workflowRunningData?.tracing || []}+ onShowIterationDetail={handleShowIterationDetail}+ />+ )}+ {currentTab === 'TRACING' && !workflowRunningData?.tracing?.length && (+ <div className='flex h-full items-center justify-center bg-gray-50'>+ <Loading />+ </div>+ )}++ </div></>)}- {currentTab === 'DETAIL' && (- <ResultPanel- inputs={workflowRunningData?.result?.inputs}- outputs={workflowRunningData?.result?.outputs}- status={workflowRunningData?.result?.status || ''}- error={workflowRunningData?.result?.error}- elapsed_time={workflowRunningData?.result?.elapsed_time}- total_tokens={workflowRunningData?.result?.total_tokens}- created_at={workflowRunningData?.result?.created_at}- created_by={(workflowRunningData?.result?.created_by as any)?.name}- steps={workflowRunningData?.result?.total_steps}- />- )}- {currentTab === 'DETAIL' && !workflowRunningData?.result && (- <div className='flex h-full items-center justify-center bg-white'>- <Loading />- </div>- )}- {currentTab === 'TRACING' && (- <TracingPanel- list={workflowRunningData?.tracing || []}- />- )}- {currentTab === 'TRACING' && !workflowRunningData?.tracing?.length && (- <div className='flex h-full items-center justify-center bg-gray-50'>- <Loading />- </div>- )}- </div></div></div>)diff --git a/web/app/components/workflow/run/index.tsx b/web/app/components/workflow/run/index.tsxindex ffcfa463305..795c80038e0 100644--- a/web/app/components/workflow/run/index.tsx+++ b/web/app/components/workflow/run/index.tsx@@ -4,9 +4,12 @@ import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'import { useContext } from 'use-context-selector'import { useTranslation } from 'react-i18next'import cn from 'classnames'+import { useBoolean } from 'ahooks'+import { BlockEnum } from '../types'import OutputPanel from './output-panel'import ResultPanel from './result-panel'import TracingPanel from './tracing-panel'+import IterationResultPanel from './iteration-result-panel'import { ToastContext } from '@/app/components/base/toast'import Loading from '@/app/components/base/loading'import { fetchRunDetail, fetchTracingList } from '@/service/log'@@ -19,9 +22,10 @@ export type RunProps = {activeTab?: 'RESULT' | 'DETAIL' | 'TRACING'runID: stringgetResultCallback?: (result: WorkflowRunDetailResponse) => void+ onShowIterationDetail: (detail: NodeTracing[][]) => void}-const RunPanel: FC<RunProps> = ({ hideResult, activeTab = 'RESULT', runID, getResultCallback }) => {+const RunPanel: FC<RunProps> = ({ hideResult, activeTab = 'RESULT', runID, getResultCallback, onShowIterationDetail }) => {const { t } = useTranslation()const { notify } = useContext(ToastContext)const [currentTab, setCurrentTab] = useState<string>(activeTab)@@ -56,12 +60,76 @@ const RunPanel: FC<RunProps> = ({ hideResult, activeTab = 'RESULT', runID, getRe}}, [notify, getResultCallback])+ const formatNodeList = useCallback((list: NodeTracing[]) => {+ const allItems = list.reverse()+ const result: NodeTracing[] = []+ let iterationIndexInfos: {+ start: number+ end: number+ }[] = []+ allItems.forEach((item) => {+ const { node_type, index, execution_metadata } = item+ if (node_type !== BlockEnum.Iteration) {+ let isInIteration = false+ let isIterationFirstNode = false+ iterationIndexInfos.forEach(({ start, end }) => {+ if (index >= start && index < end) {+ if (index === start)+ isIterationFirstNode = true++ isInIteration = true+ }+ })+ if (isInIteration) {+ const iterationDetails = result[result.length - 1].details!+ if (isIterationFirstNode)+ iterationDetails!.push([item])++ else+ iterationDetails[iterationDetails.length - 1].push(item)++ return+ }+ // not in iteration+ result.push(item)++ return+ }++ const { steps_boundary } = execution_metadata+ iterationIndexInfos = []+ steps_boundary.forEach((boundary, index) => {+ if (index === 0) {+ iterationIndexInfos.push({+ start: boundary,+ end: 0,+ })+ }+ else if (index === steps_boundary.length - 1) {+ iterationIndexInfos[iterationIndexInfos.length - 1].end = boundary+ }+ else {+ iterationIndexInfos[iterationIndexInfos.length - 1].end = boundary+ iterationIndexInfos.push({+ start: boundary,+ end: 0,+ })+ }+ })+ result.push({+ ...item,+ details: [],+ })+ })+ return result+ }, [])+const getTracingList = useCallback(async (appID: string, runID: string) => {try {const { data: nodeList } = await fetchTracingList({url: `/apps/${appID}/workflow-runs/${runID}/node-executions`,})- setList(nodeList.reverse())+ setList(formatNodeList(nodeList))}catch (err) {notify({@@ -103,6 +171,29 @@ const RunPanel: FC<RunProps> = ({ hideResult, activeTab = 'RESULT', runID, getReadjustResultHeight()}, [loading])+ const [iterationRunResult, setIterationRunResult] = useState<NodeTracing[][]>([])+ const [isShowIterationDetail, {+ setTrue: doShowIterationDetail,+ setFalse: doHideIterationDetail,+ }] = useBoolean(false)++ const handleShowIterationDetail = useCallback((detail: NodeTracing[][]) => {+ setIterationRunResult(detail)+ doShowIterationDetail()+ }, [doShowIterationDetail])++ if (isShowIterationDetail) {+ return (+ <div className='grow relative flex flex-col'>+ <IterationResultPanel+ list={iterationRunResult}+ onHide={doHideIterationDetail}+ onBack={doHideIterationDetail}+ />+ </div>+ )+ }+return (<div className='grow relative flex flex-col'>{/* tab */}@@ -161,6 +252,7 @@ const RunPanel: FC<RunProps> = ({ hideResult, activeTab = 'RESULT', runID, getRe{!loading && currentTab === 'TRACING' && (<TracingPanellist={list}+ onShowIterationDetail={handleShowIterationDetail}/>)}</div>diff --git a/web/app/components/workflow/run/iteration-result-panel.tsx b/web/app/components/workflow/run/iteration-result-panel.tsxnew file mode 100644index 00000000000..3a2487ef7c9--- /dev/null+++ b/web/app/components/workflow/run/iteration-result-panel.tsx@@ -0,0 +1,92 @@+'use client'+import type { FC } from 'react'+import React, { useCallback } from 'react'+import { useTranslation } from 'react-i18next'+import cn from 'classnames'+import { ArrowNarrowLeft } from '../../base/icons/src/vender/line/arrows'+import NodePanel from './node'+import type { NodeTracing } from '@/types/workflow'+import { XClose } from '@/app/components/base/icons/src/vender/line/general'+const i18nPrefix = 'workflow.singleRun'++type Props = {+ list: NodeTracing[][]+ onHide: () => void+ onBack: () => void+ noWrap?: boolean+}++const IterationResultPanel: FC<Props> = ({+ list,+ onHide,+ onBack,+ noWrap,+}) => {+ const { t } = useTranslation()++ const main = (+ <>+ <div className={cn(!noWrap && 'shrink-0 ', 'pl-4 pr-3 pt-3')}>+ <div className='shrink-0 flex justify-between items-center h-8'>+ <div className='text-base font-semibold text-gray-900 truncate'>+ {t(`${i18nPrefix}.testRunIteration`)}+ </div>+ <div className='ml-2 shrink-0 p-1 cursor-pointer' onClick={onHide}>+ <XClose className='w-4 h-4 text-gray-500 ' />+ </div>+ </div>+ <div className='flex items-center py-2 space-x-1 text-primary-600 cursor-pointer' onClick={onBack}>+ <ArrowNarrowLeft className='w-4 h-4' />+ <div className='leading-[18px] text-[13px] font-medium'>{t(`${i18nPrefix}.back`)}</div>+ </div>+ </div>+ {/* List */}+ <div className={cn(!noWrap ? 'h-0 grow' : 'max-h-full', 'overflow-y-auto px-4 pb-4 bg-gray-50')}>+ {list.map((iteration, index) => (+ <div key={index} className={cn('my-4', index === 0 && 'mt-2')}>+ <div className='flex items-center'>+ <div className='shrink-0 leading-[18px] text-xs font-semibold text-gray-500 uppercase'>{t(`${i18nPrefix}.iteration`)} {index + 1}</div>+ <div+ className='ml-3 grow w-0 h-px'+ style={{ background: 'linear-gradient(to right, #F3F4F6, rgba(243, 244, 246, 0))' }}+ ></div>+ </div>+ <div className='mt-0.5 space-y-1'>+ {iteration.map(node => (+ <NodePanel+ key={node.id}+ className='!px-0 !py-0'+ nodeInfo={node}+ notShowIterationNav+ />+ ))}+ </div>+ </div>+ ))}+ </div>+ </>+ )+ const handleNotBubble = useCallback((e: React.MouseEvent) => {+ // if not do this, it will trigger the message log modal disappear(useClickAway)+ e.stopPropagation()+ e.nativeEvent.stopImmediatePropagation()+ }, [])++ if (noWrap)+ return main++ return (+ <div+ className='absolute inset-0 z-10 rounded-2xl pt-10'+ style={{+ backgroundColor: 'rgba(16, 24, 40, 0.20)',+ }}+ onClick={handleNotBubble}+ >+ <div className='h-full rounded-2xl bg-white flex flex-col'>+ {main}+ </div>+ </div >+ )+}+export default React.memo(IterationResultPanel)diff --git a/web/app/components/workflow/run/node.tsx b/web/app/components/workflow/run/node.tsxindex fbab1b342f4..b9b836d0c7e 100644--- a/web/app/components/workflow/run/node.tsx+++ b/web/app/components/workflow/run/node.tsx@@ -4,23 +4,33 @@ import type { FC } from 'react'import { useCallback, useEffect, useState } from 'react'import cn from 'classnames'import BlockIcon from '../block-icon'+import { BlockEnum } from '../types'+import Split from '../nodes/_base/components/split'import CodeEditor from '@/app/components/workflow/nodes/_base/components/editor/code-editor'import { CodeLanguage } from '@/app/components/workflow/nodes/code/types'import { AlertCircle, AlertTriangle } from '@/app/components/base/icons/src/vender/line/alertsAndFeedback'import { CheckCircle, Loading02 } from '@/app/components/base/icons/src/vender/line/general'-import { ChevronRight } from '@/app/components/base/icons/src/vender/line/arrows'+import { ArrowNarrowRight, ChevronRight } from '@/app/components/base/icons/src/vender/line/arrows'import type { NodeTracing } from '@/types/workflow'type Props = {+ className?: stringnodeInfo: NodeTracinghideInfo?: booleanhideProcessDetail?: boolean+ onShowIterationDetail?: (detail: NodeTracing[][]) => void+ notShowIterationNav?: boolean+ justShowIterationNavArrow?: boolean}const NodePanel: FC<Props> = ({+ className,nodeInfo,hideInfo = false,hideProcessDetail,+ onShowIterationDetail,+ notShowIterationNav,+ justShowIterationNavArrow,}) => {const [collapseState, doSetCollapseState] = useState<boolean>(true)const setCollapseState = useCallback((state: boolean) => {@@ -51,8 +61,14 @@ const NodePanel: FC<Props> = ({setCollapseState(!nodeInfo.expand)}, [nodeInfo.expand, setCollapseState])+ const isIterationNode = nodeInfo.node_type === BlockEnum.Iteration+ const handleOnShowIterationDetail = (e: React.MouseEvent<HTMLDivElement>) => {+ e.stopPropagation()+ e.nativeEvent.stopImmediatePropagation()+ onShowIterationDetail?.(nodeInfo.details || [])+ }return (- <div className={cn('px-4 py-1', hideInfo && '!p-0')}>+ <div className={cn('px-4 py-1', className, hideInfo && '!p-0')}><div className={cn('group transition-all bg-white border border-gray-100 rounded-2xl shadow-xs hover:shadow-md', hideInfo && '!rounded-lg')}><divclassName={cn(@@ -97,6 +113,27 @@ const NodePanel: FC<Props> = ({</div>{!collapseState && !hideProcessDetail && (<div className='pb-2'>+ {/* The nav to the iteration detail */}+ {isIterationNode && !notShowIterationNav && (+ <div className='mt-2 mb-1 !px-2'>+ <div+ className='flex items-center h-[34px] justify-between px-3 bg-gray-100 border-[0.5px] border-gray-200 rounded-lg cursor-pointer'+ onClick={handleOnShowIterationDetail}>+ <div className='leading-[18px] text-[13px] font-medium text-gray-700'>{t('workflow.nodes.iteration.iteration', { count: nodeInfo.metadata?.iterator_length || (nodeInfo.execution_metadata?.steps_boundary?.length - 1) })}</div>+ {justShowIterationNavArrow+ ? (+ <ArrowNarrowRight className='w-3.5 h-3.5 text-gray-500' />+ )+ : (+ <div className='flex items-center space-x-1 text-[#155EEF]'>+ <div className='text-[13px] font-normal '>{t('workflow.common.viewDetailInTracingPanel')}</div>+ <ArrowNarrowRight className='w-3.5 h-3.5' />+ </div>+ )}+ </div>+ <Split className='mt-2' />+ </div>+ )}<div className={cn('px-[10px] py-1', hideInfo && '!px-2 !py-0.5')}>{nodeInfo.status === 'stopped' && (<div className='px-3 py-[10px] bg-[#fffaeb] rounded-lg border-[0.5px] border-[rbga(0,0,0,0.05)] text-xs leading-[18px] text-[#dc6803] shadow-xs'>{t('workflow.tracing.stopBy', { user: nodeInfo.created_by ? nodeInfo.created_by.name : 'N/A' })}</div>diff --git a/web/app/components/workflow/run/tracing-panel.tsx b/web/app/components/workflow/run/tracing-panel.tsxindex b6dc5242ea2..c80bcb41db2 100644--- a/web/app/components/workflow/run/tracing-panel.tsx+++ b/web/app/components/workflow/run/tracing-panel.tsx@@ -5,15 +5,18 @@ import type { NodeTracing } from '@/types/workflow'type TracingPanelProps = {list: NodeTracing[]+ onShowIterationDetail: (detail: NodeTracing[][]) => void}-const TracingPanel: FC<TracingPanelProps> = ({ list }) => {+const TracingPanel: FC<TracingPanelProps> = ({ list, onShowIterationDetail }) => {return (<div className='bg-gray-50 py-2'>{list.map(node => (<NodePanelkey={node.id}nodeInfo={node}+ onShowIterationDetail={onShowIterationDetail}+ justShowIterationNavArrow/>))}</div>diff --git a/web/app/components/workflow/store.ts b/web/app/components/workflow/store.tsindex 0f328134c16..7b8c1d8c99f 100644--- a/web/app/components/workflow/store.ts+++ b/web/app/components/workflow/store.ts@@ -9,6 +9,7 @@ import type {HelpLineHorizontalPosition,HelpLineVerticalPosition,} from './help-line/types'+import type { VariableAssignerNodeType } from './nodes/variable-assigner/types'import type {Edge,HistoryWorkflowData,@@ -47,6 +48,8 @@ type Shape = {setShowInputsPanel: (showInputsPanel: boolean) => voidinputs: Record<string, string>setInputs: (inputs: Record<string, string>) => void+ toolPublished: boolean+ setToolPublished: (toolPublished: boolean) => voidfiles: RunFile[]setFiles: (files: RunFile[]) => voidbackupDraft?: {@@ -69,6 +72,8 @@ type Shape = {setBuildInTools: (tools: ToolWithProvider[]) => voidcustomTools: ToolWithProvider[]setCustomTools: (tools: ToolWithProvider[]) => void+ workflowTools: ToolWithProvider[]+ setWorkflowTools: (tools: ToolWithProvider[]) => voidclipboardElements: Node[]setClipboardElements: (clipboardElements: Node[]) => voidshortcutsDisabled: boolean@@ -98,6 +103,25 @@ type Shape = {setMousePosition: (mousePosition: Shape['mousePosition']) => voidsyncWorkflowDraftHash: stringsetSyncWorkflowDraftHash: (hash: string) => void+ showConfirm?: { title: string; desc?: string; onConfirm: () => void }+ setShowConfirm: (showConfirm: Shape['showConfirm']) => void+ showAssignVariablePopup?: {+ nodeId: string+ nodeData: Node['data']+ variableAssignerNodeId: string+ variableAssignerNodeData: VariableAssignerNodeType+ variableAssignerNodeHandleId: string+ parentNode?: Node+ x: number+ y: number+ }+ setShowAssignVariablePopup: (showAssignVariablePopup: Shape['showAssignVariablePopup']) => void+ hoveringAssignVariableGroupId?: string+ setHoveringAssignVariableGroupId: (hoveringAssignVariableGroupId?: string) => void+ connectingNodePayload?: { nodeId: string; nodeType: string; handleType: string; handleId: string | null }+ setConnectingNodePayload: (startConnectingPayload?: Shape['connectingNodePayload']) => void+ enteringNodePayload?: { nodeId: string }+ setEnteringNodePayload: (enteringNodePayload?: Shape['enteringNodePayload']) => void}export const createWorkflowStore = () => {@@ -124,6 +148,8 @@ export const createWorkflowStore = () => {setShowInputsPanel: showInputsPanel => set(() => ({ showInputsPanel })),inputs: {},setInputs: inputs => set(() => ({ inputs })),+ toolPublished: false,+ setToolPublished: toolPublished => set(() => ({ toolPublished })),files: [],setFiles: files => set(() => ({ files })),backupDraft: undefined,@@ -143,6 +169,8 @@ export const createWorkflowStore = () => {setBuildInTools: buildInTools => set(() => ({ buildInTools })),customTools: [],setCustomTools: customTools => set(() => ({ customTools })),+ workflowTools: [],+ setWorkflowTools: workflowTools => set(() => ({ workflowTools })),clipboardElements: [],setClipboardElements: clipboardElements => set(() => ({ clipboardElements })),shortcutsDisabled: false,@@ -168,6 +196,16 @@ export const createWorkflowStore = () => {setMousePosition: mousePosition => set(() => ({ mousePosition })),syncWorkflowDraftHash: '',setSyncWorkflowDraftHash: syncWorkflowDraftHash => set(() => ({ syncWorkflowDraftHash })),+ showConfirm: undefined,+ setShowConfirm: showConfirm => set(() => ({ showConfirm })),+ showAssignVariablePopup: undefined,+ setShowAssignVariablePopup: showAssignVariablePopup => set(() => ({ showAssignVariablePopup })),+ hoveringAssignVariableGroupId: undefined,+ setHoveringAssignVariableGroupId: hoveringAssignVariableGroupId => set(() => ({ hoveringAssignVariableGroupId })),+ connectingNodePayload: undefined,+ setConnectingNodePayload: connectingNodePayload => set(() => ({ connectingNodePayload })),+ enteringNodePayload: undefined,+ setEnteringNodePayload: enteringNodePayload => set(() => ({ enteringNodePayload })),}))}diff --git a/web/app/components/workflow/types.ts b/web/app/components/workflow/types.tsindex c21887a5bfb..69b488344d6 100644--- a/web/app/components/workflow/types.ts+++ b/web/app/components/workflow/types.ts@@ -21,7 +21,10 @@ export enum BlockEnum {TemplateTransform = 'template-transform',HttpRequest = 'http-request',VariableAssigner = 'variable-assigner',+ VariableAggregator = 'variable-aggregator',Tool = 'tool',+ ParameterExtractor = 'parameter-extractor',+ Iteration = 'iteration',}export type Branch = {@@ -30,7 +33,6 @@ export type Branch = {}export type CommonNodeType<T = {}> = {- _isInvalidConnection?: boolean_connectedSourceHandleIds?: string[]_connectedTargetHandleIds?: string[]_targetBranches?: Branch[]@@ -39,10 +41,21 @@ export type CommonNodeType<T = {}> = {_singleRunningStatus?: NodeRunningStatus_isCandidate?: boolean_isBundled?: boolean+ _children?: string[]+ _isEntering?: boolean+ _showAddVariablePopup?: boolean+ _holdAddVariablePopup?: boolean+ _iterationLength?: number+ _iterationIndex?: number+ isIterationStart?: boolean+ isInIteration?: boolean+ iteration_id?: stringselected?: booleantitle: stringdesc: stringtype: BlockEnum+ width?: number+ height?: number} & T & Partial<Pick<ToolDefaultValue, 'provider_id' | 'provider_type' | 'provider_name' | 'tool_name'>>export type CommonEdgeType = {@@ -51,6 +64,8 @@ export type CommonEdgeType = {_connectedNodeIsSelected?: boolean_runned?: boolean_isBundled?: boolean+ isInIteration?: boolean+ iteration_id?: stringsourceType: BlockEnumtargetType: BlockEnum}@@ -101,6 +116,7 @@ export enum InputVarType {files = 'files',json = 'json', // obj, arraycontexts = 'contexts', // knowledge retrieval+ iterator = 'iterator', // iteration input}export type InputVar = {@@ -173,6 +189,7 @@ export enum VarType {arrayNumber = 'array[number]',arrayObject = 'array[object]',arrayFile = 'array[file]',+ any = 'any',}export type Var = {diff --git a/web/app/components/workflow/utils.ts b/web/app/components/workflow/utils.tsindex 19ebec5b711..48d578c451d 100644--- a/web/app/components/workflow/utils.ts+++ b/web/app/components/workflow/utils.ts@@ -3,7 +3,7 @@ import {getConnectedEdges,getOutgoers,} from 'reactflow'-import dagre from 'dagre'+import dagre from '@dagrejs/dagre'import { v4 as uuid4 } from 'uuid'import {cloneDeep,@@ -17,6 +17,7 @@ import type {} from './types'import { BlockEnum } from './types'import {+ ITERATION_NODE_Z_INDEX,NODE_WIDTH_X_OFFSET,START_INITIAL_POSITION,} from './constants'@@ -93,6 +94,16 @@ export const initialNodes = (originNodes: Node[], originEdges: Edge[]) => {})}+ const iterationNodeMap = nodes.reduce((acc, node) => {+ if (node.parentId) {+ if (acc[node.parentId])+ acc[node.parentId].push(node.id)+ else+ acc[node.parentId] = [node.id]+ }+ return acc+ }, {} as Record<string, string[]>)+return nodes.map((node) => {node.type = 'custom'@@ -119,6 +130,9 @@ export const initialNodes = (originNodes: Node[], originEdges: Edge[]) => {})}+ if (node.data.type === BlockEnum.Iteration)+ node.data._children = iterationNodeMap[node.id] || []+return node})}@@ -172,19 +186,25 @@ export const initialEdges = (originEdges: Edge[], originNodes: Node[]) => {})}-const dagreGraph = new dagre.graphlib.Graph()-dagreGraph.setDefaultEdgeLabel(() => ({}))export const getLayoutByDagre = (originNodes: Node[], originEdges: Edge[]) => {- const nodes = cloneDeep(originNodes)- const edges = cloneDeep(originEdges)+ const dagreGraph = new dagre.graphlib.Graph()+ dagreGraph.setDefaultEdgeLabel(() => ({}))+ const nodes = cloneDeep(originNodes).filter(node => !node.parentId)+ const edges = cloneDeep(originEdges).filter(edge => !edge.data?.isInIteration)dagreGraph.setGraph({rankdir: 'LR',align: 'UL',nodesep: 40,ranksep: 60,+ ranker: 'tight-tree',+ marginx: 30,+ marginy: 200,})nodes.forEach((node) => {- dagreGraph.setNode(node.id, { width: node.width, height: node.height })+ dagreGraph.setNode(node.id, {+ width: node.width!,+ height: node.height!,+ })})edges.forEach((edge) => {@@ -204,6 +224,8 @@ export const canRunBySingle = (nodeType: BlockEnum) => {|| nodeType === BlockEnum.QuestionClassifier|| nodeType === BlockEnum.HttpRequest|| nodeType === BlockEnum.Tool+ || nodeType === BlockEnum.ParameterExtractor+ || nodeType === BlockEnum.Iteration}type ConnectedSourceOrTargetNodesChange = {@@ -254,7 +276,7 @@ export const getNodesConnectedSourceOrTargetHandleIdsMap = (changes: ConnectedSoreturn nodesConnectedSourceOrTargetHandleIdsMap}-export const generateNewNode = ({ data, position, id }: Pick<Node, 'data' | 'position'> & { id?: string }) => {+export const generateNewNode = ({ data, position, id, zIndex, ...rest }: Omit<Node, 'id'> & { id?: string }) => {return {id: id || `${Date.now()}`,type: 'custom',@@ -262,6 +284,8 @@ export const generateNewNode = ({ data, position, id }: Pick<Node, 'data' | 'posposition,targetPosition: Position.Left,sourcePosition: Position.Right,+ zIndex: data.type === BlockEnum.Iteration ? ITERATION_NODE_Z_INDEX : zIndex,+ ...rest,} as Node}@@ -287,11 +311,15 @@ export const getValidTreeNodes = (nodes: Node[], edges: Edge[]) => {if (outgoers.length) {outgoers.forEach((outgoer) => {list.push(outgoer)+ if (outgoer.data.type === BlockEnum.Iteration)+ list.push(...nodes.filter(node => node.parentId === outgoer.id))traverse(outgoer, depth + 1)})}else {list.push(root)+ if (root.data.type === BlockEnum.Iteration)+ list.push(...nodes.filter(node => node.parentId === root.id))}}@@ -307,11 +335,12 @@ export const getToolCheckParams = (toolData: ToolNodeType,buildInTools: ToolWithProvider[],customTools: ToolWithProvider[],+ workflowTools: ToolWithProvider[],language: string,) => {const { provider_id, provider_type, tool_name } = toolDataconst isBuiltIn = provider_type === CollectionType.builtIn- const currentTools = isBuiltIn ? buildInTools : customTools+ const currentTools = provider_type === CollectionType.builtIn ? buildInTools : provider_type === CollectionType.custom ? customTools : workflowToolsconst currCollection = currentTools.find(item => item.id === provider_id)const currTool = currCollection?.tools.find(tool => tool.name === tool_name)const formSchemas = currTool ? toolParametersToFormSchemas(currTool.parameters) : []diff --git a/web/i18n/en-US/app-debug.ts b/web/i18n/en-US/app-debug.tsindex bf5d1215062..a859d927d7e 100644--- a/web/i18n/en-US/app-debug.ts+++ b/web/i18n/en-US/app-debug.ts@@ -284,6 +284,7 @@ const translation = {'varName': 'Variable Name','labelName': 'Label Name','inputPlaceholder': 'Please input',+ 'content': 'Content','required': 'Required','errorMsg': {varNameRequired: 'Variable name is required',diff --git a/web/i18n/en-US/tools.ts b/web/i18n/en-US/tools.tsindex 5a98bcc6988..d425f8d74b5 100644--- a/web/i18n/en-US/tools.ts+++ b/web/i18n/en-US/tools.ts@@ -1,10 +1,12 @@const translation = {title: 'Tools',createCustomTool: 'Create Custom Tool',+ customToolTip: 'Learn more about Dify custom tools',type: {all: 'All',builtIn: 'Built-in',custom: 'Custom',+ workflow: 'Workflow',},contribute: {line1: 'I\'m interested in ',@@ -21,12 +23,26 @@ const translation = {},includeToolNum: '{{num}} tools included',addTool: 'Add Tool',+ addToolModal: {+ type: 'type',+ category: 'category',+ add: 'add',+ added: 'added',+ manageInTools: 'Manage in Tools',+ emptyTitle: 'No workflow tool available',+ emptyTip: 'Go to "Workflow -> Publish as Tool"',+ },createTool: {title: 'Create Custom Tool',editAction: 'Configure',editTitle: 'Edit Custom Tool',name: 'Name',toolNamePlaceHolder: 'Enter the tool name',+ nameForToolCall: 'Tool call name',+ nameForToolCallPlaceHolder: 'Used for machine recognition, such as getCurrentWeather, list_pets',+ nameForToolCallTip: 'Only supports numbers, letters, and underscores.',+ description: 'Description',+ descriptionPlaceholder: 'Brief description of the tool\'s purpose, e.g., get the temperature for a specific location.',schema: 'Schema',schemaPlaceHolder: 'Enter your OpenAPI schema here',viewSchemaSpec: 'View the OpenAPI-Swagger Specification',@@ -71,8 +87,24 @@ const translation = {},privacyPolicy: 'Privacy policy',privacyPolicyPlaceholder: 'Please enter privacy policy',+ toolInput: {+ title: 'Tool Input',+ name: 'Name',+ required: 'Required',+ method: 'Method',+ methodSetting: 'Setting',+ methodSettingTip: 'User fills in the tool configuration',+ methodParameter: 'Parameter',+ methodParameterTip: 'LLM fills during inference',+ label: 'Tags',+ labelPlaceholder: 'Choose tags(optional)',+ description: 'Description',+ descriptionPlaceholder: 'Description of the parameter\'s meaning',+ },customDisclaimer: 'Custom disclaimer',customDisclaimerPlaceholder: 'Please enter custom disclaimer',+ confirmTitle: 'Confirm to save ?',+ confirmTip: 'Apps using this tool will be affected',},test: {title: 'Test',@@ -112,6 +144,8 @@ const translation = {toolRemoved: 'Tool removed',notAuthorized: 'Tool not authorized',howToGet: 'How to get',+ openInStudio: 'Open in Studio',+ toolNameUsageTip: 'Tool call name for agent reasoning and prompting',}export default translationdiff --git a/web/i18n/en-US/workflow.ts b/web/i18n/en-US/workflow.tsindex 3ffad0198d5..82e2cca0447 100644--- a/web/i18n/en-US/workflow.ts+++ b/web/i18n/en-US/workflow.ts@@ -60,6 +60,13 @@ const translation = {pasteHere: 'Paste Here',pointerMode: 'Pointer Mode',handMode: 'Hand Mode',+ model: 'Model',+ workflowAsTool: 'Workflow as Tool',+ configureRequired: 'Configure Required',+ configure: 'Configure',+ manageInTools: 'Manage in Tools',+ workflowAsToolTip: 'Tool reconfiguration is required after the workflow update.',+ viewDetailInTracingPanel: 'View details',},errorMsg: {fieldRequired: '{{field}} is required',@@ -78,12 +85,18 @@ const translation = {testRun: 'Test Run ',startRun: 'Start Run',running: 'Running',+ testRunIteration: 'Test Run Iteration',+ back: 'Back',+ iteration: 'Iteration',},tabs: {'searchBlock': 'Search block','blocks': 'Blocks',- 'builtInTool': 'Built-in Tool',- 'customTool': 'Custom Tool',+ 'tools': 'Tools',+ 'allTool': 'All',+ 'builtInTool': 'Built-in',+ 'customTool': 'Custom',+ 'workflowTool': 'Workflow','question-understand': 'Question Understand','logic': 'Logic','transform': 'Transform',@@ -101,7 +114,11 @@ const translation = {'code': 'Code','template-transform': 'Template','http-request': 'HTTP Request',- 'variable-assigner': 'Variable Assigner',+ 'variable-assigner': 'Variable Aggregator',+ 'variable-aggregator': 'Variable Aggregator',+ 'iteration-start': 'Iteration Start',+ 'iteration': 'Iteration',+ 'parameter-extractor': 'Parameter Extractor',},blocksAbout: {'start': 'Define the initial parameters for launching a workflow',@@ -114,7 +131,10 @@ const translation = {'code': 'Execute a piece of Python or NodeJS code to implement custom logic','template-transform': 'Convert data to string using Jinja template syntax','http-request': 'Allow server requests to be sent over the HTTP protocol',- 'variable-assigner': 'Assign variables in different branches to the same variable to achieve unified configuration of post-nodes',+ 'variable-assigner': 'Aggregate multi-branch variables into a single variable for unified configuration of downstream nodes.',+ 'variable-aggregator': 'Aggregate multi-branch variables into a single variable for unified configuration of downstream nodes.',+ 'iteration': 'Perform multiple steps on a list object until all results are outputted.',+ 'parameter-extractor': 'Use LLM to extract structured parameters from natural language for tool invocations or HTTP requests.',},operator: {zoomIn: 'Zoom In',@@ -312,7 +332,6 @@ const translation = {variableAssigner: {title: 'Assign variables',outputType: 'Output Type',- outputVarType: 'Output Variable Type',varNotSet: 'Variable not set',noVarTip: 'Add the variables to be assigned',type: {@@ -321,9 +340,13 @@ const translation = {object: 'Object',array: 'Array',},+ aggregationGroup: 'Aggregation Group',+ aggregationGroupTip: 'Enabling this feature allows the variable aggregator to aggregate multiple sets of variables.',+ addGroup: 'Add Group',outputVars: {- output: 'Assigned variable value',+ varDescribe: '{{groupName}} output',},+ setAssignVariable: 'Set assign variable',},tool: {toAuthorize: 'To authorize',@@ -352,8 +375,42 @@ const translation = {topicPlaceholder: 'Write your topic name',addClass: 'Add Class',instruction: 'Instruction',+ instructionTip: 'Input additional instructions to help the question classifier better understand how to categorize questions.',instructionPlaceholder: 'Write your instruction',},+ parameterExtractor: {+ inputVar: 'Input Variable',+ extractParameters: 'Extract Parameters',+ importFromTool: 'Import from tools',+ addExtractParameter: 'Add Extract Parameter',+ addExtractParameterContent: {+ name: 'Name',+ namePlaceholder: 'Extract Parameter Name',+ type: 'Type',+ typePlaceholder: 'Extract Parameter Type',+ description: 'Description',+ descriptionPlaceholder: 'Extract Parameter Description',+ required: 'Required',+ requiredContent: 'Required is only used as a reference for model inference, and not for mandatory validation of parameter output.',+ },+ extractParametersNotSet: 'Extract Parameters not setup',+ instruction: 'Instruction',+ instructionTip: 'Input additional instructions to help the parameter extractor understand how to extract parameters.',+ advancedSetting: 'Advanced Setting',+ reasoningMode: 'Reasoning Mode',+ reasoningModeTip: 'You can choose the appropriate reasoning mode based on the model\'s ability to respond to instructions for function calling or prompts.',+ isSuccess: 'Is Success.On success the value is 1, on failure the value is 0.',+ errorReason: 'Error Reason',+ },+ iteration: {+ deleteTitle: 'Delete Iteration Node?',+ deleteDesc: 'Deleting the iteration node will delete all child nodes',+ input: 'Input',+ output: 'Output Variables',+ iteration_one: '{{count}} Iteration',+ iteration_other: '{{count}} Iterations',+ currentIteration: 'Current Iteration',+ },},tracing: {stopBy: 'Stop by {{user}}',diff --git a/web/i18n/zh-Hans/app-debug.ts b/web/i18n/zh-Hans/app-debug.tsindex 400c5c613cb..801f7d31bf2 100644--- a/web/i18n/zh-Hans/app-debug.ts+++ b/web/i18n/zh-Hans/app-debug.ts@@ -281,6 +281,7 @@ const translation = {'inputPlaceholder': '请输入','labelName': '显示名称','required': '必填',+ 'content': '内容','errorMsg': {varNameRequired: '变量名称必填',labelNameRequired: '显示名称必填',diff --git a/web/i18n/zh-Hans/tools.ts b/web/i18n/zh-Hans/tools.tsindex dc6cad2f198..46451d25b46 100644--- a/web/i18n/zh-Hans/tools.ts+++ b/web/i18n/zh-Hans/tools.ts@@ -1,10 +1,12 @@const translation = {title: '工具',createCustomTool: '创建自定义工具',+ customToolTip: '了解更多关于 Dify 自定义工具的信息',type: {all: '全部',builtIn: '内置',custom: '自定义',+ workflow: '工作流',},contribute: {line1: '我有兴趣为 ',@@ -21,12 +23,26 @@ const translation = {},includeToolNum: '包含 {{num}} 个工具',addTool: '添加工具',+ addToolModal: {+ type: '类型',+ category: '类别',+ add: '添加',+ added: '已添加',+ manageInTools: '去工具列表管理',+ emptyTitle: '没有可用的工作流工具',+ emptyTip: '去 “工作流 -> 发布为工具” 添加',+ },createTool: {title: '创建自定义工具',editAction: '编辑',editTitle: '编辑自定义工具',name: '名称',toolNamePlaceHolder: '输入工具名称',+ nameForToolCall: '工具调用名称',+ nameForToolCallPlaceHolder: '用于机器识别,如 getCurrentWeather, list_pets',+ nameForToolCallTip: '仅支持数字、字母、下划线。',+ description: '工具描述',+ descriptionPlaceholder: '工具用途的简要描述,例如获取特定位置的温度。',schema: 'Schema',schemaPlaceHolder: '在此处输入您的 OpenAPI schema',viewSchemaSpec: '查看 OpenAPI-Swagger 规范',@@ -71,8 +87,24 @@ const translation = {},privacyPolicy: '隐私协议',privacyPolicyPlaceholder: '请输入隐私协议',+ toolInput: {+ title: '工具入参',+ name: '名称',+ required: '必须',+ method: '方式',+ methodSetting: '用户输入',+ methodSettingTip: '用户在工具配置中填写',+ methodParameter: 'LLM 填入',+ methodParameterTip: 'LLM 在推理过程中填写',+ label: '标签',+ labelPlaceholder: '选择标签(可选)',+ description: '描述',+ descriptionPlaceholder: '参数意义的描述',+ },customDisclaimer: '自定义免责声明',customDisclaimerPlaceholder: '请输入自定义免责声明',+ confirmTitle: '确认保存?',+ confirmTip: '发布新的工具版本可能会影响该工具已关联的应用',},test: {title: '测试',@@ -112,6 +144,8 @@ const translation = {toolRemoved: '工具已被移除',notAuthorized: '工具未授权',howToGet: '如何获取',+ openInStudio: '在工作室中打开',+ toolNameUsageTip: '工具调用名称,用于 Agent 推理和提示词',}export default translationdiff --git a/web/i18n/zh-Hans/workflow.ts b/web/i18n/zh-Hans/workflow.tsindex f9ae082f6f2..e384f590f33 100644--- a/web/i18n/zh-Hans/workflow.ts+++ b/web/i18n/zh-Hans/workflow.ts@@ -60,6 +60,13 @@ const translation = {pasteHere: '粘贴到这里',pointerMode: '指针模式',handMode: '手模式',+ model: '模型',+ workflowAsTool: '发布为工具',+ configureRequired: '需要进行配置',+ configure: '配置',+ manageInTools: '访问工具页',+ workflowAsToolTip: '工作流更新后需要重新配置工具参数',+ viewDetailInTracingPanel: '查看详细信息',},errorMsg: {fieldRequired: '{{field}} 不能为空',@@ -78,12 +85,18 @@ const translation = {testRun: '测试运行 ',startRun: '开始运行',running: '运行中',+ testRunIteration: '测试运行迭代',+ back: '返回',+ iteration: '迭代',},tabs: {'searchBlock': '搜索节点','blocks': '节点',- 'builtInTool': '内置工具',- 'customTool': '自定义工具',+ 'tools': '工具',+ 'allTool': '全部',+ 'builtInTool': '内置',+ 'customTool': '自定义',+ 'workflowTool': '工作流','question-understand': '问题理解','logic': '逻辑','transform': '转换',@@ -101,7 +114,11 @@ const translation = {'code': '代码执行','template-transform': '模板转换','http-request': 'HTTP 请求',- 'variable-assigner': '变量赋值',+ 'variable-assigner': '变量聚合器',+ 'variable-aggregator': '变量聚合器',+ 'iteration-start': '迭代开始',+ 'iteration': '迭代',+ 'parameter-extractor': '参数提取器',},blocksAbout: {'start': '定义一个 workflow 流程启动的初始参数',@@ -114,7 +131,10 @@ const translation = {'code': '执行一段 Python 或 NodeJS 代码实现自定义逻辑','template-transform': '使用 Jinja 模板语法将数据转换为字符串','http-request': '允许通过 HTTP 协议发送服务器请求',- 'variable-assigner': '将不同分支中的变量指派给同一个变量,以实现后置节点统一配置',+ 'variable-assigner': '将多路分支的变量聚合为一个变量,以实现下游节点统一配置。',+ 'variable-aggregator': '将多路分支的变量聚合为一个变量,以实现下游节点统一配置。',+ 'iteration': '对列表对象执行多次步骤直至输出所有结果。',+ 'parameter-extractor': '利用 LLM 从自然语言内推理提取出结构化参数,用于后置的工具调用或 HTTP 请求。',},operator: {zoomIn: '放大',@@ -312,7 +332,6 @@ const translation = {variableAssigner: {title: '变量赋值',outputType: '输出类型',- outputVarType: '输出变量类型',varNotSet: '未设置变量',noVarTip: '添加需要赋值的变量',type: {@@ -321,9 +340,13 @@ const translation = {object: 'Object',array: 'Array',},+ aggregationGroup: '聚合分组',+ aggregationGroupTip: '开启该功能后,变量聚合器内可以同时聚合多组变量',+ addGroup: '添加分组',outputVars: {- output: '指派的变量值',+ varDescribe: '{{groupName}}的输出变量',},+ setAssignVariable: '设置赋值变量',},tool: {toAuthorize: '授权',@@ -352,8 +375,42 @@ const translation = {topicPlaceholder: '在这里输入你的主题内容',addClass: '添加分类',instruction: '指令',+ instructionTip: '你可以输入额外的附加指令,帮助问题分类器更好的理解如何分类',instructionPlaceholder: '在这里输入你的指令',},+ parameterExtractor: {+ inputVar: '输入变量',+ extractParameters: '提取参数',+ importFromTool: '从工具导入',+ addExtractParameter: '添加提取参数',+ addExtractParameterContent: {+ name: '名称',+ namePlaceholder: '提取参数名称',+ type: '类型',+ typePlaceholder: '提取参数类型',+ description: '描述',+ descriptionPlaceholder: '提取参数描述',+ required: '必填',+ requiredContent: '必填仅作为模型推理的参考,不用于参数输出的强制验证。',+ },+ extractParametersNotSet: '提取参数未设置',+ instruction: '指令',+ instructionTip: '你可以输入额外的附加指令,帮助参数提取器理解如何提取参数',+ advancedSetting: '高级设置',+ reasoningMode: '推理模式',+ reasoningModeTip: '你可以根据模型对于 Function calling 或 Prompt 的指令响应能力选择合适的推理模式',+ isSuccess: '是否成功。成功时值为 1,失败时值为 0。',+ errorReason: '错误原因',+ },+ iteration: {+ deleteTitle: '删除迭代节点?',+ deleteDesc: '删除迭代节点将删除所有子节点',+ input: '输入',+ output: '输出变量',+ iteration_one: '{{count}}个迭代',+ iteration_other: '{{count}}个迭代',+ currentIteration: '当前迭代',+ },},tracing: {stopBy: '由{{user}}终止',diff --git a/web/package.json b/web/package.jsonindex fc995b2ec5e..3f990ded164 100644--- a/web/package.json+++ b/web/package.json@@ -16,6 +16,7 @@},"dependencies": {"@babel/runtime": "^7.22.3",+ "@dagrejs/dagre": "^1.1.2","@emoji-mart/data": "^1.1.2","@floating-ui/react": "^0.25.2","@formatjs/intl-localematcher": "^0.5.4",@@ -35,7 +36,6 @@"classnames": "^2.3.2","copy-to-clipboard": "^3.3.3","crypto-js": "^4.2.0",- "dagre": "^0.8.5","dayjs": "^1.11.7","echarts": "^5.4.1","echarts-for-react": "^3.0.2",@@ -73,7 +73,7 @@"react-tooltip": "5.8.3","react-window": "^1.8.9","react-window-infinite-loader": "^1.0.9",- "reactflow": "^11.10.3",+ "reactflow": "^11.11.3","recordrtc": "^5.6.2","rehype-katex": "^6.0.2","remark-breaks": "^3.0.2",diff --git a/web/service/base.ts b/web/service/base.tsindex c500e31d7ef..c4cea6f9950 100644--- a/web/service/base.ts+++ b/web/service/base.ts@@ -3,6 +3,9 @@ import Toast from '@/app/components/base/toast'import type { AnnotationReply, MessageEnd, MessageReplace, ThoughtItem } from '@/app/components/app/chat/type'import type { VisionFile } from '@/types/app'import type {+ IterationFinishedResponse,+ IterationNextedResponse,+ IterationStartedResponse,NodeFinishedResponse,NodeStartedResponse,TextChunkResponse,@@ -52,6 +55,9 @@ export type IOnWorkflowStarted = (workflowStarted: WorkflowStartedResponse) => vexport type IOnWorkflowFinished = (workflowFinished: WorkflowFinishedResponse) => voidexport type IOnNodeStarted = (nodeStarted: NodeStartedResponse) => voidexport type IOnNodeFinished = (nodeFinished: NodeFinishedResponse) => void+export type IOnIterationStarted = (workflowStarted: IterationStartedResponse) => void+export type IOnIterationNexted = (workflowStarted: IterationNextedResponse) => void+export type IOnIterationFinished = (workflowFinished: IterationFinishedResponse) => voidexport type IOnTextChunk = (textChunk: TextChunkResponse) => voidexport type IOnTextReplace = (textReplace: TextReplaceResponse) => void@@ -74,6 +80,9 @@ export type IOtherOptions = {onWorkflowFinished?: IOnWorkflowFinishedonNodeStarted?: IOnNodeStartedonNodeFinished?: IOnNodeFinished+ onIterationStart?: IOnIterationStarted+ onIterationNext?: IOnIterationNexted+ onIterationFinish?: IOnIterationFinishedonTextChunk?: IOnTextChunkonTextReplace?: IOnTextReplace}@@ -122,6 +131,9 @@ const handleStream = (onWorkflowFinished?: IOnWorkflowFinished,onNodeStarted?: IOnNodeStarted,onNodeFinished?: IOnNodeFinished,+ onIterationStart?: IOnIterationStarted,+ onIterationNext?: IOnIterationNexted,+ onIterationFinish?: IOnIterationFinished,onTextChunk?: IOnTextChunk,onTextReplace?: IOnTextReplace,) => {@@ -200,6 +212,15 @@ const handleStream = (else if (bufferObj.event === 'node_finished') {onNodeFinished?.(bufferObj as NodeFinishedResponse)}+ else if (bufferObj.event === 'iteration_started') {+ onIterationStart?.(bufferObj as IterationStartedResponse)+ }+ else if (bufferObj.event === 'iteration_next') {+ onIterationNext?.(bufferObj as IterationNextedResponse)+ }+ else if (bufferObj.event === 'iteration_completed') {+ onIterationFinish?.(bufferObj as IterationFinishedResponse)+ }else if (bufferObj.event === 'text_chunk') {onTextChunk?.(bufferObj as TextChunkResponse)}@@ -450,6 +471,9 @@ export const ssePost = (onWorkflowFinished,onNodeStarted,onNodeFinished,+ onIterationStart,+ onIterationNext,+ onIterationFinish,onTextChunk,onTextReplace,onError,@@ -503,7 +527,7 @@ export const ssePost = (return}onData?.(str, isFirstMessage, moreInfo)- }, onCompleted, onThought, onMessageEnd, onMessageReplace, onFile, onWorkflowStarted, onWorkflowFinished, onNodeStarted, onNodeFinished, onTextChunk, onTextReplace)+ }, onCompleted, onThought, onMessageEnd, onMessageReplace, onFile, onWorkflowStarted, onWorkflowFinished, onNodeStarted, onNodeFinished, onIterationStart, onIterationNext, onIterationFinish, onTextChunk, onTextReplace)}).catch((e) => {if (e.toString() !== 'AbortError: The user aborted a request.')Toast.notify({ type: 'error', message: e })diff --git a/web/service/share.ts b/web/service/share.tsindex 9f3936d84d7..14a14e266d6 100644--- a/web/service/share.ts+++ b/web/service/share.ts@@ -1,4 +1,4 @@-import type { IOnCompleted, IOnData, IOnError, IOnFile, IOnMessageEnd, IOnMessageReplace, IOnNodeFinished, IOnNodeStarted, IOnTextChunk, IOnTextReplace, IOnThought, IOnWorkflowFinished, IOnWorkflowStarted } from './base'+import type { IOnCompleted, IOnData, IOnError, IOnFile, IOnIterationFinished, IOnIterationNexted, IOnIterationStarted, IOnMessageEnd, IOnMessageReplace, IOnNodeFinished, IOnNodeStarted, IOnTextChunk, IOnTextReplace, IOnThought, IOnWorkflowFinished, IOnWorkflowStarted } from './base'import {del as consoleDel, get as consoleGet, patch as consolePatch, post as consolePost,delPublic as del, getPublic as get, patchPublic as patch, postPublic as post, ssePost,@@ -73,6 +73,9 @@ export const sendWorkflowMessage = async (onNodeStarted,onNodeFinished,onWorkflowFinished,+ onIterationStart,+ onIterationNext,+ onIterationFinish,onTextChunk,onTextReplace,}: {@@ -80,6 +83,9 @@ export const sendWorkflowMessage = async (onNodeStarted: IOnNodeStartedonNodeFinished: IOnNodeFinishedonWorkflowFinished: IOnWorkflowFinished+ onIterationStart: IOnIterationStarted+ onIterationNext: IOnIterationNexted+ onIterationFinish: IOnIterationFinishedonTextChunk: IOnTextChunkonTextReplace: IOnTextReplace},@@ -91,7 +97,7 @@ export const sendWorkflowMessage = async (...body,response_mode: 'streaming',},- }, { onNodeStarted, onWorkflowStarted, onWorkflowFinished, isPublicAPI: !isInstalledApp, onNodeFinished, onTextChunk, onTextReplace })+ }, { onNodeStarted, onWorkflowStarted, onWorkflowFinished, isPublicAPI: !isInstalledApp, onNodeFinished, onIterationStart, onIterationNext, onIterationFinish, onTextChunk, onTextReplace })}export const fetchAppInfo = async () => {diff --git a/web/service/tools.ts b/web/service/tools.tsindex 36b918d9e5a..90221edec23 100644--- a/web/service/tools.ts+++ b/web/service/tools.ts@@ -1,6 +1,15 @@import { get, post } from './base'-import type { Collection, CustomCollectionBackend, CustomParamSchema, Tool, ToolCredential } from '@/app/components/tools/types'+import type {+ Collection,+ CustomCollectionBackend,+ CustomParamSchema,+ Tool,+ ToolCredential,+ WorkflowToolProviderRequest,+ WorkflowToolProviderResponse,+} from '@/app/components/tools/types'import type { ToolWithProvider } from '@/app/components/workflow/types'+import type { Label } from '@/app/components/tools/labels/constant'export const fetchCollectionList = () => {return get<Collection[]>('/workspaces/current/tool-providers')@@ -18,6 +27,10 @@ export const fetchModelToolList = (collectionName: string) => {return get<Tool[]>(`/workspaces/current/tool-provider/model/tools?provider=${collectionName}`)}+export const fetchWorkflowToolList = (appID: string) => {+ return get<Tool[]>(`/workspaces/current/tool-provider/workflow/tools?workflow_tool_id=${appID}`)+}+export const fetchBuiltInToolCredentialSchema = (collectionName: string) => {return get<ToolCredential[]>(`/workspaces/current/tool-provider/builtin/${collectionName}/credentials_schema`)}@@ -98,3 +111,42 @@ export const fetchAllBuiltInTools = () => {export const fetchAllCustomTools = () => {return get<ToolWithProvider[]>('/workspaces/current/tools/api')}++export const fetchAllWorkflowTools = () => {+ return get<ToolWithProvider[]>('/workspaces/current/tools/workflow')+}++export const fetchLabelList = () => {+ return get<Label[]>('/workspaces/current/tool-labels')+}++export const createWorkflowToolProvider = (payload: WorkflowToolProviderRequest & { workflow_app_id: string }) => {+ return post('/workspaces/current/tool-provider/workflow/create', {+ body: { ...payload },+ })+}++export const saveWorkflowToolProvider = (payload: WorkflowToolProviderRequest & Partial<{+ workflow_app_id: string+ workflow_tool_id: string+}>) => {+ return post('/workspaces/current/tool-provider/workflow/update', {+ body: { ...payload },+ })+}++export const fetchWorkflowToolDetailByAppID = (appID: string) => {+ return get<WorkflowToolProviderResponse>(`/workspaces/current/tool-provider/workflow/get?workflow_app_id=${appID}`)+}++export const fetchWorkflowToolDetail = (toolID: string) => {+ return get<WorkflowToolProviderResponse>(`/workspaces/current/tool-provider/workflow/get?workflow_tool_id=${toolID}`)+}++export const deleteWorkflowTool = (toolID: string) => {+ return post('/workspaces/current/tool-provider/workflow/delete', {+ body: {+ workflow_tool_id: toolID,+ },+ })+}diff --git a/web/service/workflow.ts b/web/service/workflow.tsindex affe4aedf97..3cf524d481b 100644--- a/web/service/workflow.ts+++ b/web/service/workflow.ts@@ -33,6 +33,10 @@ export const singleNodeRun = (appId: string, nodeId: string, params: object) =>return post(`apps/${appId}/workflows/draft/nodes/${nodeId}/run`, { body: params })}+export const getIterationSingleNodeRunUrl = (isChatFlow: boolean, appId: string, nodeId: string) => {+ return `apps/${appId}/${isChatFlow ? 'advanced-chat/' : ''}workflows/draft/iteration/nodes/${nodeId}/run`+}+export const publishWorkflow = (url: string) => {return post<CommonResponse & { created_at: number }>(url)}diff --git a/web/types/workflow.ts b/web/types/workflow.tsindex b5c49b353f4..a24ff8169ef 100644--- a/web/types/workflow.ts+++ b/web/types/workflow.ts@@ -22,6 +22,10 @@ export type NodeTracing = {total_tokens: numbertotal_price: numbercurrency: string+ steps_boundary: number[]+ }+ metadata: {+ iterator_length: number}created_at: numbercreated_by: {@@ -32,6 +36,7 @@ export type NodeTracing = {finished_at: numberextras?: anyexpand?: boolean // for UI+ details?: NodeTracing[][] // iteration detail}export type FetchWorkflowDraftResponse = {@@ -50,6 +55,7 @@ export type FetchWorkflowDraftResponse = {}hash: stringupdated_at: number+ tool_published: boolean}export type NodeTracingListResponse = {@@ -82,6 +88,11 @@ export type WorkflowFinishedResponse = {total_tokens: numbertotal_steps: numbercreated_at: number+ created_by: {+ id: string+ name: string+ email: string+ }finished_at: number}}@@ -127,6 +138,50 @@ export type NodeFinishedResponse = {}}+export type IterationStartedResponse = {+ task_id: string+ workflow_run_id: string+ event: string+ data: {+ id: string+ node_id: string+ metadata: {+ iterator_length: number+ }+ created_at: number+ extras?: any+ }+}++export type IterationNextedResponse = {+ task_id: string+ workflow_run_id: string+ event: string+ data: {+ id: string+ node_id: string+ index: number+ output: any+ extras?: any+ created_at: number+ }+}++export type IterationFinishedResponse = {+ task_id: string+ workflow_run_id: string+ event: string+ data: {+ id: string+ node_id: string+ outputs: any+ extras?: any+ status: string+ created_at: number+ error: string+ }+}+export type TextChunkResponse = {task_id: stringworkflow_run_id: stringdiff --git a/web/yarn.lock b/web/yarn.lockindex 0fea151c252..e75fa8d0686 100644--- a/web/yarn.lock+++ b/web/yarn.lock@@ -105,6 +105,18 @@resolved "https://registry.npmjs.org/@braintree/sanitize-url/-/sanitize-url-6.0.4.tgz"integrity sha512-s3jaWicZd0pkP0jf5ysyHUI/RE7MHos6qlToFcGWXVp+ykHOy77OUMrfbgJ9it2C5bow7OIQwYYaHjk9XlBQ2A==+"@dagrejs/dagre@^1.1.2":+ version "1.1.2"+ resolved "https://registry.yarnpkg.com/@dagrejs/dagre/-/dagre-1.1.2.tgz#5ec339979447091f48d2144deed8c70dfadae374"+ integrity sha512-F09dphqvHsbe/6C2t2unbmpr5q41BNPEfJCdn8Z7aEBpVSy/zFQ/b4SWsweQjWNsYMDvE2ffNUN8X0CeFsEGNw==+ dependencies:+ "@dagrejs/graphlib" "2.2.2"++"@dagrejs/[email protected]":+ version "2.2.2"+ resolved "https://registry.yarnpkg.com/@dagrejs/graphlib/-/graphlib-2.2.2.tgz#74154d5cb880a23b4fae71034a09b4b5aef06feb"+ integrity sha512-CbyGpCDKsiTg/wuk79S7Muoj8mghDGAESWGxcSyhHX5jD35vYMBZochYVFzlHxynpE9unpu6O+4ZuhrLxASsOg==+"@emnapi/runtime@^0.45.0":version "0.45.0"resolved "https://registry.npmjs.org/@emnapi/runtime/-/runtime-0.45.0.tgz#e754de04c683263f34fd0c7f32adfe718bbe4ddd"@@ -711,28 +723,28 @@picocolors "^1.0.0"tslib "^2.5.0"-"@reactflow/[email protected]":- version "11.3.8"- resolved "https://registry.npmjs.org/@reactflow/background/-/background-11.3.8.tgz"- integrity sha512-U4aI54F7PwqgYI0Knv72QFRI/wXeipPmIYAlDsA0j51+tlPxs3Nk2z7G1/4pC11GxEZkgQVfcIXro4l1Fk+bIQ==+"@reactflow/[email protected]":+ version "11.3.13"+ resolved "https://registry.yarnpkg.com/@reactflow/background/-/background-11.3.13.tgz#a29bcdce01b5e881a330067bfd08c58c12fc7266"+ integrity sha512-hkvpVEhgvfTDyCvdlitw4ioKCYLaaiRXnuEG+1QM3Np+7N1DiWF1XOv5I8AFyNoJL07yXEkbECUTsHvkBvcG5A==dependencies:- "@reactflow/core" "11.10.3"+ "@reactflow/core" "11.11.3"classcat "^5.0.3"zustand "^4.4.1"-"@reactflow/[email protected]":- version "11.2.8"- resolved "https://registry.npmjs.org/@reactflow/controls/-/controls-11.2.8.tgz"- integrity sha512-Y9YVx38sRjYtbPsI/xa+B1FGN73FV1GqqajlmGfrc1TmqhJaX+gaMXMvVazT/N5haK1hMJvOApUTLQ2V/5Rdbg==+"@reactflow/[email protected]":+ version "11.2.13"+ resolved "https://registry.yarnpkg.com/@reactflow/controls/-/controls-11.2.13.tgz#a05d86b82fc49e8ed0ca35d04c838a45f90f4f15"+ integrity sha512-3xgEg6ALIVkAQCS4NiBjb7ad8Cb3D8CtA7Vvl4Hf5Ar2PIVs6FOaeft9s2iDZGtsWP35ECDYId1rIFVhQL8r+A==dependencies:- "@reactflow/core" "11.10.3"+ "@reactflow/core" "11.11.3"classcat "^5.0.3"zustand "^4.4.1"-"@reactflow/[email protected]":- version "11.10.3"- resolved "https://registry.npmjs.org/@reactflow/core/-/core-11.10.3.tgz"- integrity sha512-nV3nep4fjBy3h8mYSnJcclGcQtj8fkUBmNkEwCZCK4ps+n3HNkXFB0BRisSnQz6GRQlYboSsi0cThEl3KdNITw==+"@reactflow/[email protected]":+ version "11.11.3"+ resolved "https://registry.yarnpkg.com/@reactflow/core/-/core-11.11.3.tgz#2cdc0c684931918125d505bec3cb94f115b87747"+ integrity sha512-+adHdUa7fJSEM93fWfjQwyWXeI92a1eLKwWbIstoCakHpL8UjzwhEh6sn+mN2h/59MlVI7Ehr1iGTt3MsfcIFA==dependencies:"@types/d3" "^7.4.0""@types/d3-drag" "^3.0.1"@@ -744,12 +756,12 @@d3-zoom "^3.0.0"zustand "^4.4.1"-"@reactflow/[email protected]":- version "11.7.8"- resolved "https://registry.npmjs.org/@reactflow/minimap/-/minimap-11.7.8.tgz"- integrity sha512-MwyP5q3VomC91Dhd4P6YcxEfnjDbREGYV6rRxbSJSTHiG0x7ETQCcPelYDGy7JvQej77Pa2yJ4g0FDwP7CsQEA==+"@reactflow/[email protected]":+ version "11.7.13"+ resolved "https://registry.yarnpkg.com/@reactflow/minimap/-/minimap-11.7.13.tgz#99396175065a1e2d058b8639883d13c71777764f"+ integrity sha512-m2MvdiGSyOu44LEcERDEl1Aj6x//UQRWo3HEAejNU4HQTlJnYrSN8tgrYF8TxC1+c/9UdyzQY5VYgrTwW4QWdg==dependencies:- "@reactflow/core" "11.10.3"+ "@reactflow/core" "11.11.3""@types/d3-selection" "^3.0.3""@types/d3-zoom" "^3.0.1"classcat "^5.0.3"@@ -757,23 +769,23 @@d3-zoom "^3.0.0"zustand "^4.4.1"-"@reactflow/[email protected]":- version "2.2.8"- resolved "https://registry.npmjs.org/@reactflow/node-resizer/-/node-resizer-2.2.8.tgz"- integrity sha512-u/EXLpvOfAmq1sGoPYwoX4gi0PnCi0mH3eHVClHNc8JQD0WCqcV1UeVV7H3PF+1SGhhg/aOv/vPG1PcQ5fu4jQ==+"@reactflow/[email protected]":+ version "2.2.13"+ resolved "https://registry.yarnpkg.com/@reactflow/node-resizer/-/node-resizer-2.2.13.tgz#83faf6e2977f40b528bf100c0da634e08f8fb51a"+ integrity sha512-X7ceQ2s3jFLgbkg03n2RYr4hm3jTVrzkW2W/8ANv/SZfuVmF8XJxlERuD8Eka5voKqLda0ywIZGAbw9GoHLfUQ==dependencies:- "@reactflow/core" "11.10.3"+ "@reactflow/core" "11.11.3"classcat "^5.0.4"d3-drag "^3.0.0"d3-selection "^3.0.0"zustand "^4.4.1"-"@reactflow/[email protected]":- version "1.3.8"- resolved "https://registry.npmjs.org/@reactflow/node-toolbar/-/node-toolbar-1.3.8.tgz"- integrity sha512-cfvlTPeJa/ciQTosx2bGrjHT8K/UL9kznpvpOzeZFnJm5UQXmbwAYt4Vo6GfkD51mORcIL7ujQJvB9ym3ZI9KA==+"@reactflow/[email protected]":+ version "1.3.13"+ resolved "https://registry.yarnpkg.com/@reactflow/node-toolbar/-/node-toolbar-1.3.13.tgz#f15a2e6ed89287a33c4305d3bd7f3991b85db4af"+ integrity sha512-aknvNICO10uWdthFSpgD6ctY/CTBeJUMV9co8T9Ilugr08Nb89IQ4uD0dPmr031ewMQxixtYIkw+sSDDzd2aaQ==dependencies:- "@reactflow/core" "11.10.3"+ "@reactflow/core" "11.11.3"classcat "^5.0.3"zustand "^4.4.1"@@ -2362,14 +2374,6 @@ [email protected]:d3 "^7.8.2"lodash-es "^4.17.21"-dagre@^0.8.5:- version "0.8.5"- resolved "https://registry.npmjs.org/dagre/-/dagre-0.8.5.tgz"- integrity sha512-/aTqmnRta7x7MCCpExk7HQL2O4owCT2h8NT//9I1OQ9vt29Pa0BzSAkR5lwFUcQ7491yVi/3CXU9jQ5o0Mn2Sw==- dependencies:- graphlib "^2.1.8"- lodash "^4.17.15"-damerau-levenshtein@^1.0.8:version "1.0.8"resolved "https://registry.npmjs.org/damerau-levenshtein/-/damerau-levenshtein-1.0.8.tgz"@@ -3486,13 +3490,6 @@ grapheme-splitter@^1.0.4:resolved "https://registry.npmjs.org/grapheme-splitter/-/grapheme-splitter-1.0.4.tgz"integrity sha512-bzh50DW9kTPM00T8y4o8vQg89Di9oLJVLW/KaOGIXJWP/iqCN6WKYkbNOF04vFLJhwcpYUh9ydh/+5vpOqV4YQ==-graphlib@^2.1.8:- version "2.1.8"- resolved "https://registry.npmjs.org/graphlib/-/graphlib-2.1.8.tgz"- integrity sha512-jcLLfkpoVGmH7/InMC/1hIvOPSUh38oJtGhvrOFGzioE1DZ+0YW16RgmOJhHiuWTvGiJQ9Z1Ik43JvkRPRvE+A==- dependencies:- lodash "^4.17.15"-has-bigints@^1.0.1, has-bigints@^1.0.2:version "1.0.2"resolved "https://registry.npmjs.org/has-bigints/-/has-bigints-1.0.2.tgz"@@ -4377,7 +4374,7 @@ lodash.merge@^4.6.2:resolved "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz"integrity sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==-lodash@^4.17.14, lodash@^4.17.15, lodash@^4.17.21:+lodash@^4.17.14, lodash@^4.17.21:version "4.17.21"resolved "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz"integrity sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==@@ -5882,17 +5879,17 @@ react@~18.2.0:dependencies:loose-envify "^1.1.0"-reactflow@^11.10.3:- version "11.10.3"- resolved "https://registry.npmjs.org/reactflow/-/reactflow-11.10.3.tgz"- integrity sha512-DGNrTdkWjZtPOhj5MV8fiWWGkJo+otMVdoJ9l67bQL+Xf+8NkJ4AHmRXoYIxtgcENzwTr5WTAIJlswV9i91cyw==- dependencies:- "@reactflow/background" "11.3.8"- "@reactflow/controls" "11.2.8"- "@reactflow/core" "11.10.3"- "@reactflow/minimap" "11.7.8"- "@reactflow/node-resizer" "2.2.8"- "@reactflow/node-toolbar" "1.3.8"+reactflow@^11.11.3:+ version "11.11.3"+ resolved "https://registry.yarnpkg.com/reactflow/-/reactflow-11.11.3.tgz#5e8d8b395bd443c6d10d7cef2101866ed185a1e0"+ integrity sha512-wusd1Xpn1wgsSEv7UIa4NNraCwH9syBtubBy4xVNXg3b+CDKM+sFaF3hnMx0tr0et4km9urIDdNvwm34QiZong==+ dependencies:+ "@reactflow/background" "11.3.13"+ "@reactflow/controls" "11.2.13"+ "@reactflow/core" "11.11.3"+ "@reactflow/minimap" "11.7.13"+ "@reactflow/node-resizer" "2.2.13"+ "@reactflow/node-toolbar" "1.3.13"read-cache@^1.0.0:version "1.0.0"