use-workflow.ts 18 KB

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