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

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