use-workflow.ts 14 KB

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