use-workflow.ts 18 KB

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