use-workflow.ts 17 KB

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