use-workflow.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. import {
  2. useCallback,
  3. useEffect,
  4. useMemo,
  5. useState,
  6. } from 'react'
  7. import dayjs from 'dayjs'
  8. import { uniqBy } from 'lodash-es'
  9. import { useContext } from 'use-context-selector'
  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 type { FetchWorkflowDraftResponse } from '@/types/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 nodesMap = nodes.map(node => ({ ...node, data: { ...node.data, selected: false } }))
  283. eventEmitter?.emit({
  284. type: WORKFLOW_DATA_UPDATE,
  285. payload: {
  286. nodes: initialNodes(nodesMap, edges),
  287. edges: initialEdges(edges, nodesMap),
  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, setData] = useState<FetchWorkflowDraftResponse>()
  353. const [isLoading, setIsLoading] = useState(true)
  354. workflowStore.setState({ appId: appDetail.id })
  355. const handleGetInitialWorkflowData = useCallback(async () => {
  356. try {
  357. const res = await fetchWorkflowDraft(`/apps/${appDetail.id}/workflows/draft`)
  358. setData(res)
  359. setIsLoading(false)
  360. }
  361. catch (error: any) {
  362. if (error && error.json && !error.bodyUsed && appDetail) {
  363. error.json().then((err: any) => {
  364. if (err.code === 'draft_workflow_not_exist') {
  365. workflowStore.setState({ notInitialWorkflow: true })
  366. syncWorkflowDraft({
  367. url: `/apps/${appDetail.id}/workflows/draft`,
  368. params: {
  369. graph: {
  370. nodes: nodesTemplate,
  371. edges: edgesTemplate,
  372. },
  373. features: {},
  374. },
  375. }).then((res) => {
  376. workflowStore.getState().setDraftUpdatedAt(res.updated_at)
  377. handleGetInitialWorkflowData()
  378. })
  379. }
  380. })
  381. }
  382. }
  383. }, [appDetail, nodesTemplate, edgesTemplate, workflowStore])
  384. useEffect(() => {
  385. handleGetInitialWorkflowData()
  386. }, [])
  387. const handleFetchPreloadData = useCallback(async () => {
  388. try {
  389. const nodesDefaultConfigsData = await fetchNodesDefaultConfigs(`/apps/${appDetail?.id}/workflows/default-workflow-block-configs`)
  390. const publishedWorkflow = await fetchPublishedWorkflow(`/apps/${appDetail?.id}/workflows/publish`)
  391. workflowStore.setState({
  392. nodesDefaultConfigs: nodesDefaultConfigsData.reduce((acc, block) => {
  393. if (!acc[block.type])
  394. acc[block.type] = { ...block.config }
  395. return acc
  396. }, {} as Record<string, any>),
  397. })
  398. workflowStore.getState().setPublishedAt(publishedWorkflow?.created_at)
  399. }
  400. catch (e) {
  401. }
  402. }, [workflowStore, appDetail])
  403. useEffect(() => {
  404. handleFetchPreloadData()
  405. handleFetchAllTools('builtin')
  406. handleFetchAllTools('custom')
  407. }, [handleFetchPreloadData, handleFetchAllTools])
  408. useEffect(() => {
  409. if (data)
  410. workflowStore.getState().setDraftUpdatedAt(data.updated_at)
  411. }, [data, workflowStore])
  412. return {
  413. data,
  414. isLoading,
  415. }
  416. }
  417. export const useWorkflowReadOnly = () => {
  418. const workflowStore = useWorkflowStore()
  419. const workflowRunningData = useStore(s => s.workflowRunningData)
  420. const getWorkflowReadOnly = useCallback(() => {
  421. return workflowStore.getState().workflowRunningData?.result.status === WorkflowRunningStatus.Running
  422. }, [workflowStore])
  423. return {
  424. workflowReadOnly: workflowRunningData?.result.status === WorkflowRunningStatus.Running,
  425. getWorkflowReadOnly,
  426. }
  427. }
  428. export const useNodesReadOnly = () => {
  429. const workflowStore = useWorkflowStore()
  430. const workflowRunningData = useStore(s => s.workflowRunningData)
  431. const historyWorkflowData = useStore(s => s.historyWorkflowData)
  432. const isRestoring = useStore(s => s.isRestoring)
  433. const getNodesReadOnly = useCallback(() => {
  434. const {
  435. workflowRunningData,
  436. historyWorkflowData,
  437. isRestoring,
  438. } = workflowStore.getState()
  439. return workflowRunningData || historyWorkflowData || isRestoring
  440. }, [workflowStore])
  441. return {
  442. nodesReadOnly: !!(workflowRunningData || historyWorkflowData || isRestoring),
  443. getNodesReadOnly,
  444. }
  445. }
  446. export const useToolIcon = (data: Node['data']) => {
  447. const buildInTools = useStore(s => s.buildInTools)
  448. const customTools = useStore(s => s.customTools)
  449. const toolIcon = useMemo(() => {
  450. if (data.type === BlockEnum.Tool) {
  451. if (data.provider_type === 'builtin')
  452. return buildInTools.find(toolWithProvider => toolWithProvider.id === data.provider_id)?.icon
  453. return customTools.find(toolWithProvider => toolWithProvider.id === data.provider_id)?.icon
  454. }
  455. }, [data, buildInTools, customTools])
  456. return toolIcon
  457. }