index.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. 'use client'
  2. import type { FC } from 'react'
  3. import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
  4. import { useContext } from 'use-context-selector'
  5. import { useTranslation } from 'react-i18next'
  6. import { useBoolean } from 'ahooks'
  7. import { BlockEnum } from '../types'
  8. import OutputPanel from './output-panel'
  9. import ResultPanel from './result-panel'
  10. import TracingPanel from './tracing-panel'
  11. import IterationResultPanel from './iteration-result-panel'
  12. import RetryResultPanel from './retry-result-panel'
  13. import cn from '@/utils/classnames'
  14. import { ToastContext } from '@/app/components/base/toast'
  15. import Loading from '@/app/components/base/loading'
  16. import { fetchRunDetail, fetchTracingList } from '@/service/log'
  17. import type { IterationDurationMap, NodeTracing } from '@/types/workflow'
  18. import type { WorkflowRunDetailResponse } from '@/models/log'
  19. import { useStore as useAppStore } from '@/app/components/app/store'
  20. export type RunProps = {
  21. hideResult?: boolean
  22. activeTab?: 'RESULT' | 'DETAIL' | 'TRACING'
  23. runID: string
  24. getResultCallback?: (result: WorkflowRunDetailResponse) => void
  25. }
  26. const RunPanel: FC<RunProps> = ({ hideResult, activeTab = 'RESULT', runID, getResultCallback }) => {
  27. const { t } = useTranslation()
  28. const { notify } = useContext(ToastContext)
  29. const [currentTab, setCurrentTab] = useState<string>(activeTab)
  30. const appDetail = useAppStore(state => state.appDetail)
  31. const [loading, setLoading] = useState<boolean>(true)
  32. const [runDetail, setRunDetail] = useState<WorkflowRunDetailResponse>()
  33. const [list, setList] = useState<NodeTracing[]>([])
  34. const executor = useMemo(() => {
  35. if (runDetail?.created_by_role === 'account')
  36. return runDetail.created_by_account?.name || ''
  37. if (runDetail?.created_by_role === 'end_user')
  38. return runDetail.created_by_end_user?.session_id || ''
  39. return 'N/A'
  40. }, [runDetail])
  41. const getResult = useCallback(async (appID: string, runID: string) => {
  42. try {
  43. const res = await fetchRunDetail({
  44. appID,
  45. runID,
  46. })
  47. setRunDetail(res)
  48. if (getResultCallback)
  49. getResultCallback(res)
  50. }
  51. catch (err) {
  52. notify({
  53. type: 'error',
  54. message: `${err}`,
  55. })
  56. }
  57. }, [notify, getResultCallback])
  58. const formatNodeList = useCallback((list: NodeTracing[]) => {
  59. const allItems = [...list].reverse()
  60. const result: NodeTracing[] = []
  61. const nodeGroupMap = new Map<string, Map<string, NodeTracing[]>>()
  62. const processIterationNode = (item: NodeTracing) => {
  63. result.push({
  64. ...item,
  65. details: [],
  66. })
  67. }
  68. const updateParallelModeGroup = (runId: string, item: NodeTracing, iterationNode: NodeTracing) => {
  69. if (!nodeGroupMap.has(iterationNode.node_id))
  70. nodeGroupMap.set(iterationNode.node_id, new Map())
  71. const groupMap = nodeGroupMap.get(iterationNode.node_id)!
  72. if (!groupMap.has(runId)) {
  73. groupMap.set(runId, [item])
  74. }
  75. else {
  76. if (item.status === 'retry') {
  77. const retryNode = groupMap.get(runId)!.find(node => node.node_id === item.node_id)
  78. if (retryNode) {
  79. if (retryNode?.retryDetail)
  80. retryNode.retryDetail.push(item)
  81. else
  82. retryNode.retryDetail = [item]
  83. }
  84. }
  85. else {
  86. groupMap.get(runId)!.push(item)
  87. }
  88. }
  89. if (item.status === 'failed') {
  90. iterationNode.status = 'failed'
  91. iterationNode.error = item.error
  92. }
  93. iterationNode.details = Array.from(groupMap.values())
  94. }
  95. const updateSequentialModeGroup = (index: number, item: NodeTracing, iterationNode: NodeTracing) => {
  96. const { details } = iterationNode
  97. if (details) {
  98. if (!details[index]) {
  99. details[index] = [item]
  100. }
  101. else {
  102. if (item.status === 'retry') {
  103. const retryNode = details[index].find(node => node.node_id === item.node_id)
  104. if (retryNode) {
  105. if (retryNode?.retryDetail)
  106. retryNode.retryDetail.push(item)
  107. else
  108. retryNode.retryDetail = [item]
  109. }
  110. }
  111. else {
  112. details[index].push(item)
  113. }
  114. }
  115. }
  116. if (item.status === 'failed') {
  117. iterationNode.status = 'failed'
  118. iterationNode.error = item.error
  119. }
  120. }
  121. const processNonIterationNode = (item: NodeTracing) => {
  122. const { execution_metadata } = item
  123. if (!execution_metadata?.iteration_id) {
  124. if (item.status === 'retry') {
  125. const retryNode = result.find(node => node.node_id === item.node_id)
  126. if (retryNode) {
  127. if (retryNode?.retryDetail)
  128. retryNode.retryDetail.push(item)
  129. else
  130. retryNode.retryDetail = [item]
  131. }
  132. return
  133. }
  134. result.push(item)
  135. return
  136. }
  137. const iterationNode = result.find(node => node.node_id === execution_metadata.iteration_id)
  138. if (!iterationNode || !Array.isArray(iterationNode.details))
  139. return
  140. const { parallel_mode_run_id, iteration_index = 0 } = execution_metadata
  141. if (parallel_mode_run_id)
  142. updateParallelModeGroup(parallel_mode_run_id, item, iterationNode)
  143. else
  144. updateSequentialModeGroup(iteration_index, item, iterationNode)
  145. }
  146. allItems.forEach((item) => {
  147. item.node_type === BlockEnum.Iteration
  148. ? processIterationNode(item)
  149. : processNonIterationNode(item)
  150. })
  151. return result
  152. }, [])
  153. const getTracingList = useCallback(async (appID: string, runID: string) => {
  154. try {
  155. const { data: nodeList } = await fetchTracingList({
  156. url: `/apps/${appID}/workflow-runs/${runID}/node-executions`,
  157. })
  158. setList(formatNodeList(nodeList))
  159. }
  160. catch (err) {
  161. notify({
  162. type: 'error',
  163. message: `${err}`,
  164. })
  165. }
  166. }, [notify])
  167. const getData = async (appID: string, runID: string) => {
  168. setLoading(true)
  169. await getResult(appID, runID)
  170. await getTracingList(appID, runID)
  171. setLoading(false)
  172. }
  173. const switchTab = async (tab: string) => {
  174. setCurrentTab(tab)
  175. if (tab === 'RESULT')
  176. appDetail?.id && await getResult(appDetail.id, runID)
  177. appDetail?.id && await getTracingList(appDetail.id, runID)
  178. }
  179. useEffect(() => {
  180. // fetch data
  181. if (appDetail && runID)
  182. getData(appDetail.id, runID)
  183. }, [appDetail, runID])
  184. const [height, setHeight] = useState(0)
  185. const ref = useRef<HTMLDivElement>(null)
  186. const adjustResultHeight = () => {
  187. if (ref.current)
  188. setHeight(ref.current?.clientHeight - 16 - 16 - 2 - 1)
  189. }
  190. useEffect(() => {
  191. adjustResultHeight()
  192. }, [loading])
  193. const [iterationRunResult, setIterationRunResult] = useState<NodeTracing[][]>([])
  194. const [iterDurationMap, setIterDurationMap] = useState<IterationDurationMap>({})
  195. const [retryRunResult, setRetryRunResult] = useState<NodeTracing[]>([])
  196. const [isShowIterationDetail, {
  197. setTrue: doShowIterationDetail,
  198. setFalse: doHideIterationDetail,
  199. }] = useBoolean(false)
  200. const [isShowRetryDetail, {
  201. setTrue: doShowRetryDetail,
  202. setFalse: doHideRetryDetail,
  203. }] = useBoolean(false)
  204. const handleShowIterationDetail = useCallback((detail: NodeTracing[][], iterDurationMap: IterationDurationMap) => {
  205. setIterationRunResult(detail)
  206. doShowIterationDetail()
  207. setIterDurationMap(iterDurationMap)
  208. }, [doShowIterationDetail, setIterationRunResult, setIterDurationMap])
  209. const handleShowRetryDetail = useCallback((detail: NodeTracing[]) => {
  210. setRetryRunResult(detail)
  211. doShowRetryDetail()
  212. }, [doShowRetryDetail, setRetryRunResult])
  213. if (isShowIterationDetail) {
  214. return (
  215. <div className='grow relative flex flex-col'>
  216. <IterationResultPanel
  217. list={iterationRunResult}
  218. onHide={doHideIterationDetail}
  219. onBack={doHideIterationDetail}
  220. iterDurationMap={iterDurationMap}
  221. />
  222. </div>
  223. )
  224. }
  225. return (
  226. <div className='grow relative flex flex-col'>
  227. {/* tab */}
  228. <div className='shrink-0 flex items-center px-4 border-b-[0.5px] border-divider-subtle'>
  229. {!hideResult && (
  230. <div
  231. className={cn(
  232. 'mr-6 py-3 border-b-2 border-transparent system-sm-semibold-uppercase text-text-tertiary cursor-pointer',
  233. currentTab === 'RESULT' && '!border-util-colors-blue-brand-blue-brand-600 text-text-primary',
  234. )}
  235. onClick={() => switchTab('RESULT')}
  236. >{t('runLog.result')}</div>
  237. )}
  238. <div
  239. className={cn(
  240. 'mr-6 py-3 border-b-2 border-transparent system-sm-semibold-uppercase text-text-tertiary cursor-pointer',
  241. currentTab === 'DETAIL' && '!border-util-colors-blue-brand-blue-brand-600 text-text-primary',
  242. )}
  243. onClick={() => switchTab('DETAIL')}
  244. >{t('runLog.detail')}</div>
  245. <div
  246. className={cn(
  247. 'mr-6 py-3 border-b-2 border-transparent system-sm-semibold-uppercase text-text-tertiary cursor-pointer',
  248. currentTab === 'TRACING' && '!border-util-colors-blue-brand-blue-brand-600 text-text-primary',
  249. )}
  250. onClick={() => switchTab('TRACING')}
  251. >{t('runLog.tracing')}</div>
  252. </div>
  253. {/* panel detail */}
  254. <div ref={ref} className={cn('grow bg-components-panel-bg h-0 overflow-y-auto rounded-b-2xl', currentTab !== 'DETAIL' && '!bg-background-section-burn')}>
  255. {loading && (
  256. <div className='flex h-full items-center justify-center bg-components-panel-bg'>
  257. <Loading />
  258. </div>
  259. )}
  260. {!loading && currentTab === 'RESULT' && runDetail && (
  261. <OutputPanel
  262. outputs={runDetail.outputs}
  263. error={runDetail.error}
  264. height={height}
  265. />
  266. )}
  267. {!loading && currentTab === 'DETAIL' && runDetail && (
  268. <ResultPanel
  269. inputs={runDetail.inputs}
  270. outputs={runDetail.outputs}
  271. status={runDetail.status}
  272. error={runDetail.error}
  273. elapsed_time={runDetail.elapsed_time}
  274. total_tokens={runDetail.total_tokens}
  275. created_at={runDetail.created_at}
  276. created_by={executor}
  277. steps={runDetail.total_steps}
  278. exceptionCounts={runDetail.exceptions_count}
  279. />
  280. )}
  281. {!loading && currentTab === 'TRACING' && !isShowRetryDetail && (
  282. <TracingPanel
  283. className='bg-background-section-burn'
  284. list={list}
  285. onShowIterationDetail={handleShowIterationDetail}
  286. onShowRetryDetail={handleShowRetryDetail}
  287. />
  288. )}
  289. {
  290. !loading && currentTab === 'TRACING' && isShowRetryDetail && (
  291. <RetryResultPanel
  292. list={retryRunResult}
  293. onBack={doHideRetryDetail}
  294. />
  295. )
  296. }
  297. </div>
  298. </div>
  299. )
  300. }
  301. export default RunPanel