use-workflow.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. import {
  2. useCallback,
  3. useEffect,
  4. useMemo,
  5. } from 'react'
  6. import dayjs from 'dayjs'
  7. import { uniqBy } from 'lodash-es'
  8. import { useContext } from 'use-context-selector'
  9. import useSWR from 'swr'
  10. import produce from 'immer'
  11. import {
  12. getIncomers,
  13. getOutgoers,
  14. useReactFlow,
  15. useStoreApi,
  16. } from 'reactflow'
  17. import type {
  18. Connection,
  19. Viewport,
  20. } from 'reactflow'
  21. import {
  22. getLayoutByDagre,
  23. initialEdges,
  24. initialNodes,
  25. } from '../utils'
  26. import type {
  27. Edge,
  28. Node,
  29. ValueSelector,
  30. } from '../types'
  31. import {
  32. BlockEnum,
  33. WorkflowRunningStatus,
  34. } from '../types'
  35. import {
  36. useStore,
  37. useWorkflowStore,
  38. } from '../store'
  39. import {
  40. AUTO_LAYOUT_OFFSET,
  41. SUPPORT_OUTPUT_VARS_NODE,
  42. } from '../constants'
  43. import { findUsedVarNodes, getNodeOutputVars, updateNodeVars } from '../nodes/_base/components/variable/utils'
  44. import { useNodesExtraData } from './use-nodes-data'
  45. import { useWorkflowTemplate } from './use-workflow-template'
  46. import { useNodesSyncDraft } from './use-nodes-sync-draft'
  47. import { useStore as useAppStore } from '@/app/components/app/store'
  48. import {
  49. fetchNodesDefaultConfigs,
  50. fetchPublishedWorkflow,
  51. fetchWorkflowDraft,
  52. syncWorkflowDraft,
  53. } from '@/service/workflow'
  54. import {
  55. fetchAllBuiltInTools,
  56. fetchAllCustomTools,
  57. } from '@/service/tools'
  58. import I18n from '@/context/i18n'
  59. export const useIsChatMode = () => {
  60. const appDetail = useAppStore(s => s.appDetail)
  61. return appDetail?.mode === 'advanced-chat'
  62. }
  63. export const useWorkflow = () => {
  64. const { locale } = useContext(I18n)
  65. const store = useStoreApi()
  66. const reactflow = useReactFlow()
  67. const workflowStore = useWorkflowStore()
  68. const nodesExtraData = useNodesExtraData()
  69. const { handleSyncWorkflowDraft } = useNodesSyncDraft()
  70. const handleLayout = useCallback(async () => {
  71. workflowStore.setState({ nodeAnimation: true })
  72. const {
  73. getNodes,
  74. edges,
  75. setNodes,
  76. } = store.getState()
  77. const { setViewport } = reactflow
  78. const nodes = getNodes()
  79. const layout = getLayoutByDagre(nodes, edges)
  80. const newNodes = produce(nodes, (draft) => {
  81. draft.forEach((node) => {
  82. const nodeWithPosition = layout.node(node.id)
  83. node.position = {
  84. x: nodeWithPosition.x + AUTO_LAYOUT_OFFSET.x,
  85. y: nodeWithPosition.y + AUTO_LAYOUT_OFFSET.y,
  86. }
  87. })
  88. })
  89. setNodes(newNodes)
  90. const zoom = 0.7
  91. setViewport({
  92. x: 0,
  93. y: 0,
  94. zoom,
  95. })
  96. setTimeout(() => {
  97. handleSyncWorkflowDraft()
  98. })
  99. }, [store, reactflow, handleSyncWorkflowDraft, workflowStore])
  100. const getTreeLeafNodes = useCallback((nodeId: string) => {
  101. const {
  102. getNodes,
  103. edges,
  104. } = store.getState()
  105. const nodes = getNodes()
  106. const startNode = nodes.find(node => node.data.type === BlockEnum.Start)
  107. if (!startNode)
  108. return []
  109. const list: Node[] = []
  110. const preOrder = (root: Node, callback: (node: Node) => void) => {
  111. if (root.id === nodeId)
  112. return
  113. const outgoers = getOutgoers(root, nodes, edges)
  114. if (outgoers.length) {
  115. outgoers.forEach((outgoer) => {
  116. preOrder(outgoer, callback)
  117. })
  118. }
  119. else {
  120. if (root.id !== nodeId)
  121. callback(root)
  122. }
  123. }
  124. preOrder(startNode, (node) => {
  125. list.push(node)
  126. })
  127. const incomers = getIncomers({ id: nodeId } as Node, nodes, edges)
  128. list.push(...incomers)
  129. return uniqBy(list, 'id').filter((item) => {
  130. return SUPPORT_OUTPUT_VARS_NODE.includes(item.data.type)
  131. })
  132. }, [store])
  133. const getBeforeNodesInSameBranch = useCallback((nodeId: string) => {
  134. const {
  135. getNodes,
  136. edges,
  137. } = store.getState()
  138. const nodes = getNodes()
  139. const currentNode = nodes.find(node => node.id === nodeId)
  140. const list: Node[] = []
  141. if (!currentNode)
  142. return list
  143. const traverse = (root: Node, callback: (node: Node) => void) => {
  144. if (root) {
  145. const incomers = getIncomers(root, nodes, edges)
  146. if (incomers.length) {
  147. incomers.forEach((node) => {
  148. if (!list.find(n => node.id === n.id)) {
  149. callback(node)
  150. traverse(node, callback)
  151. }
  152. })
  153. }
  154. }
  155. }
  156. traverse(currentNode, (node) => {
  157. list.push(node)
  158. })
  159. const length = list.length
  160. if (length) {
  161. return uniqBy(list, 'id').reverse().filter((item) => {
  162. return SUPPORT_OUTPUT_VARS_NODE.includes(item.data.type)
  163. })
  164. }
  165. return []
  166. }, [store])
  167. const getAfterNodesInSameBranch = useCallback((nodeId: string) => {
  168. const {
  169. getNodes,
  170. edges,
  171. } = store.getState()
  172. const nodes = getNodes()
  173. const currentNode = nodes.find(node => node.id === nodeId)!
  174. if (!currentNode)
  175. return []
  176. const list: Node[] = [currentNode]
  177. const traverse = (root: Node, callback: (node: Node) => void) => {
  178. if (root) {
  179. const outgoers = getOutgoers(root, nodes, edges)
  180. if (outgoers.length) {
  181. outgoers.forEach((node) => {
  182. callback(node)
  183. traverse(node, callback)
  184. })
  185. }
  186. }
  187. }
  188. traverse(currentNode, (node) => {
  189. list.push(node)
  190. })
  191. return uniqBy(list, 'id')
  192. }, [store])
  193. const getBeforeNodeById = useCallback((nodeId: string) => {
  194. const {
  195. getNodes,
  196. edges,
  197. } = store.getState()
  198. const nodes = getNodes()
  199. const node = nodes.find(node => node.id === nodeId)!
  200. return getIncomers(node, nodes, edges)
  201. }, [store])
  202. const handleOutVarRenameChange = useCallback((nodeId: string, oldValeSelector: ValueSelector, newVarSelector: ValueSelector) => {
  203. const { getNodes, setNodes } = store.getState()
  204. const afterNodes = getAfterNodesInSameBranch(nodeId)
  205. const effectNodes = findUsedVarNodes(oldValeSelector, afterNodes)
  206. // console.log(effectNodes)
  207. if (effectNodes.length > 0) {
  208. const newNodes = getNodes().map((node) => {
  209. if (effectNodes.find(n => n.id === node.id))
  210. return updateNodeVars(node, oldValeSelector, newVarSelector)
  211. return node
  212. })
  213. setNodes(newNodes)
  214. }
  215. // eslint-disable-next-line react-hooks/exhaustive-deps
  216. }, [store])
  217. const isVarUsedInNodes = useCallback((varSelector: ValueSelector) => {
  218. const nodeId = varSelector[0]
  219. const afterNodes = getAfterNodesInSameBranch(nodeId)
  220. const effectNodes = findUsedVarNodes(varSelector, afterNodes)
  221. return effectNodes.length > 0
  222. }, [getAfterNodesInSameBranch])
  223. const removeUsedVarInNodes = useCallback((varSelector: ValueSelector) => {
  224. const nodeId = varSelector[0]
  225. const { getNodes, setNodes } = store.getState()
  226. const afterNodes = getAfterNodesInSameBranch(nodeId)
  227. const effectNodes = findUsedVarNodes(varSelector, afterNodes)
  228. if (effectNodes.length > 0) {
  229. const newNodes = getNodes().map((node) => {
  230. if (effectNodes.find(n => n.id === node.id))
  231. return updateNodeVars(node, varSelector, [])
  232. return node
  233. })
  234. setNodes(newNodes)
  235. }
  236. }, [getAfterNodesInSameBranch, store])
  237. const isNodeVarsUsedInNodes = useCallback((node: Node, isChatMode: boolean) => {
  238. const outputVars = getNodeOutputVars(node, isChatMode)
  239. const isUsed = outputVars.some((varSelector) => {
  240. return isVarUsedInNodes(varSelector)
  241. })
  242. return isUsed
  243. }, [isVarUsedInNodes])
  244. const isValidConnection = useCallback(({ source, target }: Connection) => {
  245. const {
  246. edges,
  247. getNodes,
  248. } = store.getState()
  249. const nodes = getNodes()
  250. const sourceNode: Node = nodes.find(node => node.id === source)!
  251. const targetNode: Node = nodes.find(node => node.id === target)!
  252. if (sourceNode && targetNode) {
  253. const sourceNodeAvailableNextNodes = nodesExtraData[sourceNode.data.type].availableNextNodes
  254. const targetNodeAvailablePrevNodes = [...nodesExtraData[targetNode.data.type].availablePrevNodes, BlockEnum.Start]
  255. if (!sourceNodeAvailableNextNodes.includes(targetNode.data.type))
  256. return false
  257. if (!targetNodeAvailablePrevNodes.includes(sourceNode.data.type))
  258. return false
  259. }
  260. const hasCycle = (node: Node, visited = new Set()) => {
  261. if (visited.has(node.id))
  262. return false
  263. visited.add(node.id)
  264. for (const outgoer of getOutgoers(node, nodes, edges)) {
  265. if (outgoer.id === source)
  266. return true
  267. if (hasCycle(outgoer, visited))
  268. return true
  269. }
  270. }
  271. return !hasCycle(targetNode)
  272. }, [store, nodesExtraData])
  273. const formatTimeFromNow = useCallback((time: number) => {
  274. return dayjs(time).locale(locale === 'zh-Hans' ? 'zh-cn' : locale).fromNow()
  275. }, [locale])
  276. const renderTreeFromRecord = useCallback((nodes: Node[], edges: Edge[], viewport?: Viewport) => {
  277. const { setNodes } = store.getState()
  278. const { setViewport, setEdges } = reactflow
  279. setNodes(initialNodes(nodes, edges))
  280. setEdges(initialEdges(edges, nodes))
  281. if (viewport)
  282. setViewport(viewport)
  283. }, [store, reactflow])
  284. const getNode = useCallback((nodeId?: string) => {
  285. const { getNodes } = store.getState()
  286. const nodes = getNodes()
  287. return nodes.find(node => node.id === nodeId) || nodes.find(node => node.data.type === BlockEnum.Start)
  288. }, [store])
  289. return {
  290. handleLayout,
  291. getTreeLeafNodes,
  292. getBeforeNodesInSameBranch,
  293. getAfterNodesInSameBranch,
  294. handleOutVarRenameChange,
  295. isVarUsedInNodes,
  296. removeUsedVarInNodes,
  297. isNodeVarsUsedInNodes,
  298. isValidConnection,
  299. formatTimeFromNow,
  300. renderTreeFromRecord,
  301. getNode,
  302. getBeforeNodeById,
  303. }
  304. }
  305. export const useFetchToolsData = () => {
  306. const workflowStore = useWorkflowStore()
  307. const handleFetchAllTools = useCallback(async (type: string) => {
  308. if (type === 'builtin') {
  309. const buildInTools = await fetchAllBuiltInTools()
  310. workflowStore.setState({
  311. buildInTools: buildInTools || [],
  312. })
  313. }
  314. if (type === 'custom') {
  315. const customTools = await fetchAllCustomTools()
  316. workflowStore.setState({
  317. customTools: customTools || [],
  318. })
  319. }
  320. }, [workflowStore])
  321. return {
  322. handleFetchAllTools,
  323. }
  324. }
  325. export const useWorkflowInit = () => {
  326. const workflowStore = useWorkflowStore()
  327. const {
  328. nodes: nodesTemplate,
  329. edges: edgesTemplate,
  330. } = useWorkflowTemplate()
  331. const { handleFetchAllTools } = useFetchToolsData()
  332. const appDetail = useAppStore(state => state.appDetail)!
  333. const { data, isLoading, error, mutate } = useSWR(`/apps/${appDetail.id}/workflows/draft`, fetchWorkflowDraft)
  334. workflowStore.setState({ appId: appDetail.id })
  335. const handleFetchPreloadData = useCallback(async () => {
  336. try {
  337. const nodesDefaultConfigsData = await fetchNodesDefaultConfigs(`/apps/${appDetail?.id}/workflows/default-workflow-block-configs`)
  338. const publishedWorkflow = await fetchPublishedWorkflow(`/apps/${appDetail?.id}/workflows/publish`)
  339. workflowStore.setState({
  340. nodesDefaultConfigs: nodesDefaultConfigsData.reduce((acc, block) => {
  341. if (!acc[block.type])
  342. acc[block.type] = { ...block.config }
  343. return acc
  344. }, {} as Record<string, any>),
  345. })
  346. workflowStore.getState().setPublishedAt(publishedWorkflow?.created_at)
  347. }
  348. catch (e) {
  349. }
  350. }, [workflowStore, appDetail])
  351. useEffect(() => {
  352. handleFetchPreloadData()
  353. handleFetchAllTools('builtin')
  354. handleFetchAllTools('custom')
  355. }, [handleFetchPreloadData, handleFetchAllTools])
  356. useEffect(() => {
  357. if (data)
  358. workflowStore.getState().setDraftUpdatedAt(data.updated_at)
  359. }, [data, workflowStore])
  360. if (error && error.json && !error.bodyUsed && appDetail) {
  361. error.json().then((err: any) => {
  362. if (err.code === 'draft_workflow_not_exist') {
  363. workflowStore.setState({ notInitialWorkflow: true })
  364. syncWorkflowDraft({
  365. url: `/apps/${appDetail.id}/workflows/draft`,
  366. params: {
  367. graph: {
  368. nodes: nodesTemplate,
  369. edges: edgesTemplate,
  370. },
  371. features: {},
  372. },
  373. }).then((res) => {
  374. workflowStore.getState().setDraftUpdatedAt(res.updated_at)
  375. mutate()
  376. })
  377. }
  378. })
  379. }
  380. return {
  381. data,
  382. isLoading,
  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 || historyWorkflowData || isRestoring
  408. }, [workflowStore])
  409. return {
  410. nodesReadOnly: !!(workflowRunningData || 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 toolIcon = useMemo(() => {
  418. if (data.type === BlockEnum.Tool) {
  419. if (data.provider_type === 'builtin')
  420. return buildInTools.find(toolWithProvider => toolWithProvider.id === data.provider_id)?.icon
  421. return customTools.find(toolWithProvider => toolWithProvider.id === data.provider_id)?.icon
  422. }
  423. }, [data, buildInTools, customTools])
  424. return toolIcon
  425. }