Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

use-workflow.ts 16KB

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