use-workflow.ts 15 KB

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