use-workflow.ts 14 KB

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