use-workflow-node-finished.ts 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import { useCallback } from 'react'
  2. import { useStoreApi } from 'reactflow'
  3. import produce from 'immer'
  4. import type { NodeFinishedResponse } from '@/types/workflow'
  5. import {
  6. BlockEnum,
  7. NodeRunningStatus,
  8. } from '@/app/components/workflow/types'
  9. import { ErrorHandleTypeEnum } from '@/app/components/workflow/nodes/_base/components/error-handle/types'
  10. import { useWorkflowStore } from '@/app/components/workflow/store'
  11. export const useWorkflowNodeFinished = () => {
  12. const store = useStoreApi()
  13. const workflowStore = useWorkflowStore()
  14. const handleWorkflowNodeFinished = useCallback((params: NodeFinishedResponse) => {
  15. const { data } = params
  16. const {
  17. workflowRunningData,
  18. setWorkflowRunningData,
  19. } = workflowStore.getState()
  20. const {
  21. getNodes,
  22. setNodes,
  23. edges,
  24. setEdges,
  25. } = store.getState()
  26. const nodes = getNodes()
  27. setWorkflowRunningData(produce(workflowRunningData!, (draft) => {
  28. const currentIndex = draft.tracing!.findIndex(item => item.id === data.id)
  29. if (currentIndex > -1) {
  30. draft.tracing![currentIndex] = {
  31. ...draft.tracing![currentIndex],
  32. ...data,
  33. }
  34. }
  35. }))
  36. const newNodes = produce(nodes, (draft) => {
  37. const currentNode = draft.find(node => node.id === data.node_id)!
  38. currentNode.data._runningStatus = data.status
  39. if (data.status === NodeRunningStatus.Exception) {
  40. if (data.execution_metadata?.error_strategy === ErrorHandleTypeEnum.failBranch)
  41. currentNode.data._runningBranchId = ErrorHandleTypeEnum.failBranch
  42. }
  43. else {
  44. if (data.node_type === BlockEnum.IfElse)
  45. currentNode.data._runningBranchId = data?.outputs?.selected_case_id
  46. if (data.node_type === BlockEnum.QuestionClassifier)
  47. currentNode.data._runningBranchId = data?.outputs?.class_id
  48. }
  49. })
  50. setNodes(newNodes)
  51. const newEdges = produce(edges, (draft) => {
  52. const incomeEdges = draft.filter((edge) => {
  53. return edge.target === data.node_id
  54. })
  55. incomeEdges.forEach((edge) => {
  56. edge.data = {
  57. ...edge.data,
  58. _targetRunningStatus: data.status as any,
  59. }
  60. })
  61. })
  62. setEdges(newEdges)
  63. }, [store, workflowStore])
  64. return {
  65. handleWorkflowNodeFinished,
  66. }
  67. }