use-workflow.ts 14 KB

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