use-workflow-run.ts 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. import { useCallback } from 'react'
  2. import {
  3. useReactFlow,
  4. useStoreApi,
  5. } from 'reactflow'
  6. import produce from 'immer'
  7. import { useWorkflowStore } from '../store'
  8. import {
  9. NodeRunningStatus,
  10. WorkflowRunningStatus,
  11. } from '../types'
  12. import { useWorkflow } from './use-workflow'
  13. import { useStore as useAppStore } from '@/app/components/app/store'
  14. import type { IOtherOptions } from '@/service/base'
  15. import { ssePost } from '@/service/base'
  16. import {
  17. fetchPublishedWorkflow,
  18. stopWorkflowRun,
  19. } from '@/service/workflow'
  20. import { useFeaturesStore } from '@/app/components/base/features/hooks'
  21. export const useWorkflowRun = () => {
  22. const store = useStoreApi()
  23. const workflowStore = useWorkflowStore()
  24. const reactflow = useReactFlow()
  25. const featuresStore = useFeaturesStore()
  26. const { renderTreeFromRecord } = useWorkflow()
  27. const handleBackupDraft = useCallback(() => {
  28. const {
  29. getNodes,
  30. edges,
  31. } = store.getState()
  32. const { getViewport } = reactflow
  33. const {
  34. backupDraft,
  35. setBackupDraft,
  36. } = workflowStore.getState()
  37. const { features } = featuresStore!.getState()
  38. if (!backupDraft) {
  39. setBackupDraft({
  40. nodes: getNodes(),
  41. edges,
  42. viewport: getViewport(),
  43. features,
  44. })
  45. }
  46. }, [reactflow, workflowStore, store, featuresStore])
  47. const handleLoadBackupDraft = useCallback(() => {
  48. const {
  49. setNodes,
  50. setEdges,
  51. } = store.getState()
  52. const { setViewport } = reactflow
  53. const {
  54. backupDraft,
  55. setBackupDraft,
  56. } = workflowStore.getState()
  57. if (backupDraft) {
  58. const {
  59. nodes,
  60. edges,
  61. viewport,
  62. features,
  63. } = backupDraft
  64. setNodes(nodes)
  65. setEdges(edges)
  66. setViewport(viewport)
  67. featuresStore!.setState({ features })
  68. setBackupDraft(undefined)
  69. }
  70. }, [store, reactflow, workflowStore, featuresStore])
  71. const handleRunSetting = useCallback((shouldClear?: boolean) => {
  72. if (shouldClear) {
  73. workflowStore.setState({
  74. workflowRunningData: undefined,
  75. historyWorkflowData: undefined,
  76. showInputsPanel: false,
  77. })
  78. }
  79. else {
  80. workflowStore.setState({
  81. workflowRunningData: {
  82. result: {
  83. status: shouldClear ? '' : WorkflowRunningStatus.Waiting,
  84. },
  85. tracing: [],
  86. },
  87. })
  88. }
  89. const {
  90. setNodes,
  91. getNodes,
  92. edges,
  93. setEdges,
  94. } = store.getState()
  95. if (shouldClear) {
  96. handleLoadBackupDraft()
  97. }
  98. else {
  99. handleBackupDraft()
  100. const newNodes = produce(getNodes(), (draft) => {
  101. draft.forEach((node) => {
  102. node.data._runningStatus = NodeRunningStatus.Waiting
  103. })
  104. })
  105. setNodes(newNodes)
  106. const newEdges = produce(edges, (draft) => {
  107. draft.forEach((edge) => {
  108. edge.data._runned = false
  109. })
  110. })
  111. setEdges(newEdges)
  112. }
  113. }, [store, handleLoadBackupDraft, handleBackupDraft, workflowStore])
  114. const handleRun = useCallback((
  115. params: any,
  116. callback?: IOtherOptions,
  117. ) => {
  118. const {
  119. onWorkflowStarted,
  120. onWorkflowFinished,
  121. onNodeStarted,
  122. onNodeFinished,
  123. onError,
  124. ...restCallback
  125. } = callback || {}
  126. workflowStore.setState({ historyWorkflowData: undefined })
  127. const appDetail = useAppStore.getState().appDetail
  128. const workflowContainer = document.getElementById('workflow-container')
  129. const {
  130. clientWidth,
  131. clientHeight,
  132. } = workflowContainer!
  133. let url = ''
  134. if (appDetail?.mode === 'advanced-chat')
  135. url = `/apps/${appDetail.id}/advanced-chat/workflows/draft/run`
  136. if (appDetail?.mode === 'workflow')
  137. url = `/apps/${appDetail.id}/workflows/draft/run`
  138. let prevNodeId = ''
  139. const {
  140. workflowRunningData,
  141. setWorkflowRunningData,
  142. } = workflowStore.getState()
  143. setWorkflowRunningData(produce(workflowRunningData!, (draft) => {
  144. draft.result = {
  145. ...draft?.result,
  146. status: WorkflowRunningStatus.Running,
  147. }
  148. }))
  149. ssePost(
  150. url,
  151. {
  152. body: params,
  153. },
  154. {
  155. onWorkflowStarted: (params) => {
  156. const { task_id, data } = params
  157. const {
  158. workflowRunningData,
  159. setWorkflowRunningData,
  160. } = workflowStore.getState()
  161. const {
  162. getNodes,
  163. setNodes,
  164. } = store.getState()
  165. setWorkflowRunningData(produce(workflowRunningData!, (draft) => {
  166. draft.task_id = task_id
  167. draft.result = {
  168. ...draft?.result,
  169. ...data,
  170. status: WorkflowRunningStatus.Running,
  171. }
  172. }))
  173. const newNodes = produce(getNodes(), (draft) => {
  174. draft.forEach((node) => {
  175. node.data._runningStatus = NodeRunningStatus.Waiting
  176. })
  177. })
  178. setNodes(newNodes)
  179. if (onWorkflowStarted)
  180. onWorkflowStarted(params)
  181. },
  182. onWorkflowFinished: (params) => {
  183. const { data } = params
  184. const {
  185. workflowRunningData,
  186. setWorkflowRunningData,
  187. } = workflowStore.getState()
  188. setWorkflowRunningData(produce(workflowRunningData!, (draft) => {
  189. draft.result = {
  190. ...draft.result,
  191. ...data,
  192. }
  193. }))
  194. prevNodeId = ''
  195. if (onWorkflowFinished)
  196. onWorkflowFinished(params)
  197. },
  198. onError: (params) => {
  199. const {
  200. workflowRunningData,
  201. setWorkflowRunningData,
  202. } = workflowStore.getState()
  203. setWorkflowRunningData(produce(workflowRunningData!, (draft) => {
  204. draft.result = {
  205. ...draft.result,
  206. status: WorkflowRunningStatus.Failed,
  207. }
  208. }))
  209. if (onError)
  210. onError(params)
  211. },
  212. onNodeStarted: (params) => {
  213. const { data } = params
  214. const {
  215. workflowRunningData,
  216. setWorkflowRunningData,
  217. } = workflowStore.getState()
  218. const {
  219. getNodes,
  220. setNodes,
  221. edges,
  222. setEdges,
  223. } = store.getState()
  224. const nodes = getNodes()
  225. setWorkflowRunningData(produce(workflowRunningData!, (draft) => {
  226. draft.tracing!.push({
  227. ...data,
  228. status: NodeRunningStatus.Running,
  229. } as any)
  230. }))
  231. const {
  232. setViewport,
  233. } = reactflow
  234. const currentNodeIndex = nodes.findIndex(node => node.id === data.node_id)
  235. const currentNode = nodes[currentNodeIndex]
  236. const position = currentNode.position
  237. const zoom = 1
  238. setViewport({
  239. x: (clientWidth - 400 - currentNode.width!) / 2 - position.x,
  240. y: (clientHeight - currentNode.height!) / 2 - position.y,
  241. zoom,
  242. })
  243. const newNodes = produce(nodes, (draft) => {
  244. draft[currentNodeIndex].data._runningStatus = NodeRunningStatus.Running
  245. })
  246. setNodes(newNodes)
  247. const newEdges = produce(edges, (draft) => {
  248. const edge = draft.find(edge => edge.target === data.node_id && edge.source === prevNodeId)
  249. if (edge)
  250. edge.data = { ...edge.data, _runned: true } as any
  251. })
  252. setEdges(newEdges)
  253. if (onNodeStarted)
  254. onNodeStarted(params)
  255. },
  256. onNodeFinished: (params) => {
  257. const { data } = params
  258. const {
  259. workflowRunningData,
  260. setWorkflowRunningData,
  261. } = workflowStore.getState()
  262. const {
  263. getNodes,
  264. setNodes,
  265. } = store.getState()
  266. const nodes = getNodes()
  267. setWorkflowRunningData(produce(workflowRunningData!, (draft) => {
  268. const currentIndex = draft.tracing!.findIndex(trace => trace.node_id === data.node_id)
  269. if (currentIndex > -1 && draft.tracing) {
  270. draft.tracing[currentIndex] = {
  271. ...(draft.tracing[currentIndex].extras
  272. ? { extras: draft.tracing[currentIndex].extras }
  273. : {}),
  274. ...data,
  275. } as any
  276. }
  277. }))
  278. const newNodes = produce(nodes, (draft) => {
  279. const currentNode = draft.find(node => node.id === data.node_id)!
  280. currentNode.data._runningStatus = data.status as any
  281. })
  282. setNodes(newNodes)
  283. prevNodeId = data.node_id
  284. if (onNodeFinished)
  285. onNodeFinished(params)
  286. },
  287. ...restCallback,
  288. },
  289. )
  290. }, [store, reactflow, workflowStore])
  291. const handleStopRun = useCallback((taskId: string) => {
  292. const appId = useAppStore.getState().appDetail?.id
  293. stopWorkflowRun(`/apps/${appId}/workflow-runs/tasks/${taskId}/stop`)
  294. }, [])
  295. const handleRestoreFromPublishedWorkflow = useCallback(async () => {
  296. const appDetail = useAppStore.getState().appDetail
  297. const publishedWorkflow = await fetchPublishedWorkflow(`/apps/${appDetail?.id}/workflows/publish`)
  298. if (publishedWorkflow) {
  299. const nodes = publishedWorkflow.graph.nodes
  300. const edges = publishedWorkflow.graph.edges
  301. const viewport = publishedWorkflow.graph.viewport
  302. renderTreeFromRecord(nodes, edges, viewport)
  303. featuresStore?.setState({ features: publishedWorkflow.features })
  304. workflowStore.getState().setPublishedAt(publishedWorkflow.created_at)
  305. }
  306. }, [featuresStore, workflowStore, renderTreeFromRecord])
  307. return {
  308. handleBackupDraft,
  309. handleLoadBackupDraft,
  310. handleRunSetting,
  311. handleRun,
  312. handleStopRun,
  313. handleRestoreFromPublishedWorkflow,
  314. }
  315. }