You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

use-workflow.ts 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. import {
  2. useCallback,
  3. useMemo,
  4. } from 'react'
  5. import { uniqBy } from 'lodash-es'
  6. import { useTranslation } from 'react-i18next'
  7. import {
  8. getIncomers,
  9. getOutgoers,
  10. useStoreApi,
  11. } from 'reactflow'
  12. import type {
  13. Connection,
  14. } from 'reactflow'
  15. import type {
  16. Edge,
  17. Node,
  18. ValueSelector,
  19. } from '../types'
  20. import {
  21. BlockEnum,
  22. WorkflowRunningStatus,
  23. } from '../types'
  24. import {
  25. useStore,
  26. useWorkflowStore,
  27. } from '../store'
  28. import {
  29. getParallelInfo,
  30. } from '../utils'
  31. import {
  32. PARALLEL_DEPTH_LIMIT,
  33. PARALLEL_LIMIT,
  34. SUPPORT_OUTPUT_VARS_NODE,
  35. } from '../constants'
  36. import { CUSTOM_NOTE_NODE } from '../note-node/constants'
  37. import { findUsedVarNodes, getNodeOutputVars, updateNodeVars } from '../nodes/_base/components/variable/utils'
  38. import { useNodesExtraData } from './use-nodes-data'
  39. import { useStore as useAppStore } from '@/app/components/app/store'
  40. import {
  41. fetchAllBuiltInTools,
  42. fetchAllCustomTools,
  43. fetchAllMCPTools,
  44. fetchAllWorkflowTools,
  45. } from '@/service/tools'
  46. import { CollectionType } from '@/app/components/tools/types'
  47. import { CUSTOM_ITERATION_START_NODE } from '@/app/components/workflow/nodes/iteration-start/constants'
  48. import { CUSTOM_LOOP_START_NODE } from '@/app/components/workflow/nodes/loop-start/constants'
  49. import { basePath } from '@/utils/var'
  50. import { canFindTool } from '@/utils'
  51. export const useIsChatMode = () => {
  52. const appDetail = useAppStore(s => s.appDetail)
  53. return appDetail?.mode === 'advanced-chat'
  54. }
  55. export const useWorkflow = () => {
  56. const { t } = useTranslation()
  57. const store = useStoreApi()
  58. const workflowStore = useWorkflowStore()
  59. const nodesExtraData = useNodesExtraData()
  60. const getTreeLeafNodes = useCallback((nodeId: string) => {
  61. const {
  62. getNodes,
  63. edges,
  64. } = store.getState()
  65. const nodes = getNodes()
  66. let startNode = nodes.find(node => node.data.type === BlockEnum.Start)
  67. const currentNode = nodes.find(node => node.id === nodeId)
  68. if (currentNode?.parentId)
  69. startNode = nodes.find(node => node.parentId === currentNode.parentId && (node.type === CUSTOM_ITERATION_START_NODE || node.type === CUSTOM_LOOP_START_NODE))
  70. if (!startNode)
  71. return []
  72. const list: Node[] = []
  73. const preOrder = (root: Node, callback: (node: Node) => void) => {
  74. if (root.id === nodeId)
  75. return
  76. const outgoers = getOutgoers(root, nodes, edges)
  77. if (outgoers.length) {
  78. outgoers.forEach((outgoer) => {
  79. preOrder(outgoer, callback)
  80. })
  81. }
  82. else {
  83. if (root.id !== nodeId)
  84. callback(root)
  85. }
  86. }
  87. preOrder(startNode, (node) => {
  88. list.push(node)
  89. })
  90. const incomers = getIncomers({ id: nodeId } as Node, nodes, edges)
  91. list.push(...incomers)
  92. return uniqBy(list, 'id').filter((item: Node) => {
  93. return SUPPORT_OUTPUT_VARS_NODE.includes(item.data.type)
  94. })
  95. }, [store])
  96. const getBeforeNodesInSameBranch = useCallback((nodeId: string, newNodes?: Node[], newEdges?: Edge[]) => {
  97. const {
  98. getNodes,
  99. edges,
  100. } = store.getState()
  101. const nodes = newNodes || getNodes()
  102. const currentNode = nodes.find(node => node.id === nodeId)
  103. const list: Node[] = []
  104. if (!currentNode)
  105. return list
  106. if (currentNode.parentId) {
  107. const parentNode = nodes.find(node => node.id === currentNode.parentId)
  108. if (parentNode) {
  109. const parentList = getBeforeNodesInSameBranch(parentNode.id)
  110. list.push(...parentList)
  111. }
  112. }
  113. const traverse = (root: Node, callback: (node: Node) => void) => {
  114. if (root) {
  115. const incomers = getIncomers(root, nodes, newEdges || edges)
  116. if (incomers.length) {
  117. incomers.forEach((node) => {
  118. if (!list.find(n => node.id === n.id)) {
  119. callback(node)
  120. traverse(node, callback)
  121. }
  122. })
  123. }
  124. }
  125. }
  126. traverse(currentNode, (node) => {
  127. list.push(node)
  128. })
  129. const length = list.length
  130. if (length) {
  131. return uniqBy(list, 'id').reverse().filter((item: Node) => {
  132. return SUPPORT_OUTPUT_VARS_NODE.includes(item.data.type)
  133. })
  134. }
  135. return []
  136. }, [store])
  137. const getBeforeNodesInSameBranchIncludeParent = useCallback((nodeId: string, newNodes?: Node[], newEdges?: Edge[]) => {
  138. const nodes = getBeforeNodesInSameBranch(nodeId, newNodes, newEdges)
  139. const {
  140. getNodes,
  141. } = store.getState()
  142. const allNodes = getNodes()
  143. const node = allNodes.find(n => n.id === nodeId)
  144. const parentNodeId = node?.parentId
  145. const parentNode = allNodes.find(n => n.id === parentNodeId)
  146. if (parentNode)
  147. nodes.push(parentNode)
  148. return nodes
  149. }, [getBeforeNodesInSameBranch, store])
  150. const getAfterNodesInSameBranch = useCallback((nodeId: string) => {
  151. const {
  152. getNodes,
  153. edges,
  154. } = store.getState()
  155. const nodes = getNodes()
  156. const currentNode = nodes.find(node => node.id === nodeId)!
  157. if (!currentNode)
  158. return []
  159. const list: Node[] = [currentNode]
  160. const traverse = (root: Node, callback: (node: Node) => void) => {
  161. if (root) {
  162. const outgoers = getOutgoers(root, nodes, edges)
  163. if (outgoers.length) {
  164. outgoers.forEach((node) => {
  165. callback(node)
  166. traverse(node, callback)
  167. })
  168. }
  169. }
  170. }
  171. traverse(currentNode, (node) => {
  172. list.push(node)
  173. })
  174. return uniqBy(list, 'id')
  175. }, [store])
  176. const getBeforeNodeById = useCallback((nodeId: string) => {
  177. const {
  178. getNodes,
  179. edges,
  180. } = store.getState()
  181. const nodes = getNodes()
  182. const node = nodes.find(node => node.id === nodeId)!
  183. return getIncomers(node, nodes, edges)
  184. }, [store])
  185. const getIterationNodeChildren = useCallback((nodeId: string) => {
  186. const {
  187. getNodes,
  188. } = store.getState()
  189. const nodes = getNodes()
  190. return nodes.filter(node => node.parentId === nodeId)
  191. }, [store])
  192. const getLoopNodeChildren = useCallback((nodeId: string) => {
  193. const {
  194. getNodes,
  195. } = store.getState()
  196. const nodes = getNodes()
  197. return nodes.filter(node => node.parentId === nodeId)
  198. }, [store])
  199. const isFromStartNode = useCallback((nodeId: string) => {
  200. const { getNodes } = store.getState()
  201. const nodes = getNodes()
  202. const currentNode = nodes.find(node => node.id === nodeId)
  203. if (!currentNode)
  204. return false
  205. if (currentNode.data.type === BlockEnum.Start)
  206. return true
  207. const checkPreviousNodes = (node: Node) => {
  208. const previousNodes = getBeforeNodeById(node.id)
  209. for (const prevNode of previousNodes) {
  210. if (prevNode.data.type === BlockEnum.Start)
  211. return true
  212. if (checkPreviousNodes(prevNode))
  213. return true
  214. }
  215. return false
  216. }
  217. return checkPreviousNodes(currentNode)
  218. }, [store, getBeforeNodeById])
  219. const handleOutVarRenameChange = useCallback((nodeId: string, oldValeSelector: ValueSelector, newVarSelector: ValueSelector) => {
  220. const { getNodes, setNodes } = store.getState()
  221. const afterNodes = getAfterNodesInSameBranch(nodeId)
  222. const effectNodes = findUsedVarNodes(oldValeSelector, afterNodes)
  223. if (effectNodes.length > 0) {
  224. const newNodes = getNodes().map((node) => {
  225. if (effectNodes.find(n => n.id === node.id))
  226. return updateNodeVars(node, oldValeSelector, newVarSelector)
  227. return node
  228. })
  229. setNodes(newNodes)
  230. }
  231. // eslint-disable-next-line react-hooks/exhaustive-deps
  232. }, [store])
  233. const isVarUsedInNodes = useCallback((varSelector: ValueSelector) => {
  234. const nodeId = varSelector[0]
  235. const afterNodes = getAfterNodesInSameBranch(nodeId)
  236. const effectNodes = findUsedVarNodes(varSelector, afterNodes)
  237. return effectNodes.length > 0
  238. }, [getAfterNodesInSameBranch])
  239. const removeUsedVarInNodes = useCallback((varSelector: ValueSelector) => {
  240. const nodeId = varSelector[0]
  241. const { getNodes, setNodes } = store.getState()
  242. const afterNodes = getAfterNodesInSameBranch(nodeId)
  243. const effectNodes = findUsedVarNodes(varSelector, afterNodes)
  244. if (effectNodes.length > 0) {
  245. const newNodes = getNodes().map((node) => {
  246. if (effectNodes.find(n => n.id === node.id))
  247. return updateNodeVars(node, varSelector, [])
  248. return node
  249. })
  250. setNodes(newNodes)
  251. }
  252. }, [getAfterNodesInSameBranch, store])
  253. const isNodeVarsUsedInNodes = useCallback((node: Node, isChatMode: boolean) => {
  254. const outputVars = getNodeOutputVars(node, isChatMode)
  255. const isUsed = outputVars.some((varSelector) => {
  256. return isVarUsedInNodes(varSelector)
  257. })
  258. return isUsed
  259. }, [isVarUsedInNodes])
  260. const checkParallelLimit = useCallback((nodeId: string, nodeHandle = 'source') => {
  261. const {
  262. edges,
  263. } = store.getState()
  264. const connectedEdges = edges.filter(edge => edge.source === nodeId && edge.sourceHandle === nodeHandle)
  265. if (connectedEdges.length > PARALLEL_LIMIT - 1) {
  266. const { setShowTips } = workflowStore.getState()
  267. setShowTips(t('workflow.common.parallelTip.limit', { num: PARALLEL_LIMIT }))
  268. return false
  269. }
  270. return true
  271. }, [store, workflowStore, t])
  272. const checkNestedParallelLimit = useCallback((nodes: Node[], edges: Edge[], parentNodeId?: string) => {
  273. const {
  274. parallelList,
  275. hasAbnormalEdges,
  276. } = getParallelInfo(nodes, edges, parentNodeId)
  277. const { workflowConfig } = workflowStore.getState()
  278. if (hasAbnormalEdges)
  279. return false
  280. for (let i = 0; i < parallelList.length; i++) {
  281. const parallel = parallelList[i]
  282. if (parallel.depth > (workflowConfig?.parallel_depth_limit || PARALLEL_DEPTH_LIMIT)) {
  283. const { setShowTips } = workflowStore.getState()
  284. setShowTips(t('workflow.common.parallelTip.depthLimit', { num: (workflowConfig?.parallel_depth_limit || PARALLEL_DEPTH_LIMIT) }))
  285. return false
  286. }
  287. }
  288. return true
  289. }, [t, workflowStore])
  290. const isValidConnection = useCallback(({ source, sourceHandle, target }: Connection) => {
  291. const {
  292. edges,
  293. getNodes,
  294. } = store.getState()
  295. const nodes = getNodes()
  296. const sourceNode: Node = nodes.find(node => node.id === source)!
  297. const targetNode: Node = nodes.find(node => node.id === target)!
  298. if (!checkParallelLimit(source!, sourceHandle || 'source'))
  299. return false
  300. if (sourceNode.type === CUSTOM_NOTE_NODE || targetNode.type === CUSTOM_NOTE_NODE)
  301. return false
  302. if (sourceNode.parentId !== targetNode.parentId)
  303. return false
  304. if (sourceNode && targetNode) {
  305. const sourceNodeAvailableNextNodes = nodesExtraData[sourceNode.data.type].availableNextNodes
  306. const targetNodeAvailablePrevNodes = [...nodesExtraData[targetNode.data.type].availablePrevNodes, BlockEnum.Start]
  307. if (!sourceNodeAvailableNextNodes.includes(targetNode.data.type))
  308. return false
  309. if (!targetNodeAvailablePrevNodes.includes(sourceNode.data.type))
  310. return false
  311. }
  312. const hasCycle = (node: Node, visited = new Set()) => {
  313. if (visited.has(node.id))
  314. return false
  315. visited.add(node.id)
  316. for (const outgoer of getOutgoers(node, nodes, edges)) {
  317. if (outgoer.id === source)
  318. return true
  319. if (hasCycle(outgoer, visited))
  320. return true
  321. }
  322. }
  323. return !hasCycle(targetNode)
  324. }, [store, nodesExtraData, checkParallelLimit])
  325. const getNode = useCallback((nodeId?: string) => {
  326. const { getNodes } = store.getState()
  327. const nodes = getNodes()
  328. return nodes.find(node => node.id === nodeId) || nodes.find(node => node.data.type === BlockEnum.Start)
  329. }, [store])
  330. return {
  331. getTreeLeafNodes,
  332. getBeforeNodesInSameBranch,
  333. getBeforeNodesInSameBranchIncludeParent,
  334. getAfterNodesInSameBranch,
  335. handleOutVarRenameChange,
  336. isVarUsedInNodes,
  337. removeUsedVarInNodes,
  338. isNodeVarsUsedInNodes,
  339. checkParallelLimit,
  340. checkNestedParallelLimit,
  341. isValidConnection,
  342. isFromStartNode,
  343. getNode,
  344. getBeforeNodeById,
  345. getIterationNodeChildren,
  346. getLoopNodeChildren,
  347. }
  348. }
  349. export const useFetchToolsData = () => {
  350. const workflowStore = useWorkflowStore()
  351. const handleFetchAllTools = useCallback(async (type: string) => {
  352. if (type === 'builtin') {
  353. const buildInTools = await fetchAllBuiltInTools()
  354. if (basePath) {
  355. buildInTools.forEach((item) => {
  356. if (typeof item.icon == 'string' && !item.icon.includes(basePath))
  357. item.icon = `${basePath}${item.icon}`
  358. })
  359. }
  360. workflowStore.setState({
  361. buildInTools: buildInTools || [],
  362. })
  363. }
  364. if (type === 'custom') {
  365. const customTools = await fetchAllCustomTools()
  366. workflowStore.setState({
  367. customTools: customTools || [],
  368. })
  369. }
  370. if (type === 'workflow') {
  371. const workflowTools = await fetchAllWorkflowTools()
  372. workflowStore.setState({
  373. workflowTools: workflowTools || [],
  374. })
  375. }
  376. if(type === 'mcp') {
  377. const mcpTools = await fetchAllMCPTools()
  378. workflowStore.setState({
  379. mcpTools: mcpTools || [],
  380. })
  381. }
  382. }, [workflowStore])
  383. return {
  384. handleFetchAllTools,
  385. }
  386. }
  387. export const useWorkflowReadOnly = () => {
  388. const workflowStore = useWorkflowStore()
  389. const workflowRunningData = useStore(s => s.workflowRunningData)
  390. const getWorkflowReadOnly = useCallback(() => {
  391. return workflowStore.getState().workflowRunningData?.result.status === WorkflowRunningStatus.Running
  392. }, [workflowStore])
  393. return {
  394. workflowReadOnly: workflowRunningData?.result.status === WorkflowRunningStatus.Running,
  395. getWorkflowReadOnly,
  396. }
  397. }
  398. export const useNodesReadOnly = () => {
  399. const workflowStore = useWorkflowStore()
  400. const workflowRunningData = useStore(s => s.workflowRunningData)
  401. const historyWorkflowData = useStore(s => s.historyWorkflowData)
  402. const isRestoring = useStore(s => s.isRestoring)
  403. const getNodesReadOnly = useCallback(() => {
  404. const {
  405. workflowRunningData,
  406. historyWorkflowData,
  407. isRestoring,
  408. } = workflowStore.getState()
  409. return workflowRunningData?.result.status === WorkflowRunningStatus.Running || historyWorkflowData || isRestoring
  410. }, [workflowStore])
  411. return {
  412. nodesReadOnly: !!(workflowRunningData?.result.status === WorkflowRunningStatus.Running || historyWorkflowData || isRestoring),
  413. getNodesReadOnly,
  414. }
  415. }
  416. export const useToolIcon = (data: Node['data']) => {
  417. const buildInTools = useStore(s => s.buildInTools)
  418. const customTools = useStore(s => s.customTools)
  419. const workflowTools = useStore(s => s.workflowTools)
  420. const mcpTools = useStore(s => s.mcpTools)
  421. const toolIcon = useMemo(() => {
  422. if(!data)
  423. return ''
  424. if (data.type === BlockEnum.Tool) {
  425. let targetTools = buildInTools
  426. if (data.provider_type === CollectionType.builtIn)
  427. targetTools = buildInTools
  428. else if (data.provider_type === CollectionType.custom)
  429. targetTools = customTools
  430. else if (data.provider_type === CollectionType.mcp)
  431. targetTools = mcpTools
  432. else
  433. targetTools = workflowTools
  434. return targetTools.find(toolWithProvider => canFindTool(toolWithProvider.id, data.provider_id))?.icon
  435. }
  436. }, [data, buildInTools, customTools, mcpTools, workflowTools])
  437. return toolIcon
  438. }
  439. export const useIsNodeInIteration = (iterationId: string) => {
  440. const store = useStoreApi()
  441. const isNodeInIteration = useCallback((nodeId: string) => {
  442. const {
  443. getNodes,
  444. } = store.getState()
  445. const nodes = getNodes()
  446. const node = nodes.find(node => node.id === nodeId)
  447. if (!node)
  448. return false
  449. if (node.parentId === iterationId)
  450. return true
  451. return false
  452. }, [iterationId, store])
  453. return {
  454. isNodeInIteration,
  455. }
  456. }
  457. export const useIsNodeInLoop = (loopId: string) => {
  458. const store = useStoreApi()
  459. const isNodeInLoop = useCallback((nodeId: string) => {
  460. const {
  461. getNodes,
  462. } = store.getState()
  463. const nodes = getNodes()
  464. const node = nodes.find(node => node.id === nodeId)
  465. if (!node)
  466. return false
  467. if (node.parentId === loopId)
  468. return true
  469. return false
  470. }, [loopId, store])
  471. return {
  472. isNodeInLoop,
  473. }
  474. }