use-workflow.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  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. const enableShortcuts = useCallback(() => {
  290. const { setShortcutsDisabled } = workflowStore.getState()
  291. setShortcutsDisabled(false)
  292. }, [workflowStore])
  293. const disableShortcuts = useCallback(() => {
  294. const { setShortcutsDisabled } = workflowStore.getState()
  295. setShortcutsDisabled(true)
  296. }, [workflowStore])
  297. return {
  298. handleLayout,
  299. getTreeLeafNodes,
  300. getBeforeNodesInSameBranch,
  301. getAfterNodesInSameBranch,
  302. handleOutVarRenameChange,
  303. isVarUsedInNodes,
  304. removeUsedVarInNodes,
  305. isNodeVarsUsedInNodes,
  306. isValidConnection,
  307. formatTimeFromNow,
  308. renderTreeFromRecord,
  309. getNode,
  310. getBeforeNodeById,
  311. enableShortcuts,
  312. disableShortcuts,
  313. }
  314. }
  315. export const useFetchToolsData = () => {
  316. const workflowStore = useWorkflowStore()
  317. const handleFetchAllTools = useCallback(async (type: string) => {
  318. if (type === 'builtin') {
  319. const buildInTools = await fetchAllBuiltInTools()
  320. workflowStore.setState({
  321. buildInTools: buildInTools || [],
  322. })
  323. }
  324. if (type === 'custom') {
  325. const customTools = await fetchAllCustomTools()
  326. workflowStore.setState({
  327. customTools: customTools || [],
  328. })
  329. }
  330. }, [workflowStore])
  331. return {
  332. handleFetchAllTools,
  333. }
  334. }
  335. export const useWorkflowInit = () => {
  336. const workflowStore = useWorkflowStore()
  337. const {
  338. nodes: nodesTemplate,
  339. edges: edgesTemplate,
  340. } = useWorkflowTemplate()
  341. const { handleFetchAllTools } = useFetchToolsData()
  342. const appDetail = useAppStore(state => state.appDetail)!
  343. const { data, isLoading, error, mutate } = useSWR(`/apps/${appDetail.id}/workflows/draft`, fetchWorkflowDraft)
  344. workflowStore.setState({ appId: appDetail.id })
  345. const handleFetchPreloadData = useCallback(async () => {
  346. try {
  347. const nodesDefaultConfigsData = await fetchNodesDefaultConfigs(`/apps/${appDetail?.id}/workflows/default-workflow-block-configs`)
  348. const publishedWorkflow = await fetchPublishedWorkflow(`/apps/${appDetail?.id}/workflows/publish`)
  349. workflowStore.setState({
  350. nodesDefaultConfigs: nodesDefaultConfigsData.reduce((acc, block) => {
  351. if (!acc[block.type])
  352. acc[block.type] = { ...block.config }
  353. return acc
  354. }, {} as Record<string, any>),
  355. })
  356. workflowStore.getState().setPublishedAt(publishedWorkflow?.created_at)
  357. }
  358. catch (e) {
  359. }
  360. }, [workflowStore, appDetail])
  361. useEffect(() => {
  362. handleFetchPreloadData()
  363. handleFetchAllTools('builtin')
  364. handleFetchAllTools('custom')
  365. }, [handleFetchPreloadData, handleFetchAllTools])
  366. useEffect(() => {
  367. if (data)
  368. workflowStore.getState().setDraftUpdatedAt(data.updated_at)
  369. }, [data, workflowStore])
  370. if (error && error.json && !error.bodyUsed && appDetail) {
  371. error.json().then((err: any) => {
  372. if (err.code === 'draft_workflow_not_exist') {
  373. workflowStore.setState({ notInitialWorkflow: true })
  374. syncWorkflowDraft({
  375. url: `/apps/${appDetail.id}/workflows/draft`,
  376. params: {
  377. graph: {
  378. nodes: nodesTemplate,
  379. edges: edgesTemplate,
  380. },
  381. features: {},
  382. },
  383. }).then((res) => {
  384. workflowStore.getState().setDraftUpdatedAt(res.updated_at)
  385. mutate()
  386. })
  387. }
  388. })
  389. }
  390. return {
  391. data,
  392. isLoading,
  393. }
  394. }
  395. export const useWorkflowReadOnly = () => {
  396. const workflowStore = useWorkflowStore()
  397. const workflowRunningData = useStore(s => s.workflowRunningData)
  398. const getWorkflowReadOnly = useCallback(() => {
  399. return workflowStore.getState().workflowRunningData?.result.status === WorkflowRunningStatus.Running
  400. }, [workflowStore])
  401. return {
  402. workflowReadOnly: workflowRunningData?.result.status === WorkflowRunningStatus.Running,
  403. getWorkflowReadOnly,
  404. }
  405. }
  406. export const useNodesReadOnly = () => {
  407. const workflowStore = useWorkflowStore()
  408. const workflowRunningData = useStore(s => s.workflowRunningData)
  409. const historyWorkflowData = useStore(s => s.historyWorkflowData)
  410. const isRestoring = useStore(s => s.isRestoring)
  411. const getNodesReadOnly = useCallback(() => {
  412. const {
  413. workflowRunningData,
  414. historyWorkflowData,
  415. isRestoring,
  416. } = workflowStore.getState()
  417. return workflowRunningData || historyWorkflowData || isRestoring
  418. }, [workflowStore])
  419. return {
  420. nodesReadOnly: !!(workflowRunningData || historyWorkflowData || isRestoring),
  421. getNodesReadOnly,
  422. }
  423. }
  424. export const useToolIcon = (data: Node['data']) => {
  425. const buildInTools = useStore(s => s.buildInTools)
  426. const customTools = useStore(s => s.customTools)
  427. const toolIcon = useMemo(() => {
  428. if (data.type === BlockEnum.Tool) {
  429. if (data.provider_type === 'builtin')
  430. return buildInTools.find(toolWithProvider => toolWithProvider.id === data.provider_id)?.icon
  431. return customTools.find(toolWithProvider => toolWithProvider.id === data.provider_id)?.icon
  432. }
  433. }, [data, buildInTools, customTools])
  434. return toolIcon
  435. }