index.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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. else
  75. groupMap.get(runId)!.push(item)
  76. if (item.status === 'failed') {
  77. iterationNode.status = 'failed'
  78. iterationNode.error = item.error
  79. }
  80. iterationNode.details = Array.from(groupMap.values())
  81. }
  82. const updateSequentialModeGroup = (index: number, item: NodeTracing, iterationNode: NodeTracing) => {
  83. const { details } = iterationNode
  84. if (details) {
  85. if (!details[index])
  86. details[index] = [item]
  87. else
  88. details[index].push(item)
  89. }
  90. if (item.status === 'failed') {
  91. iterationNode.status = 'failed'
  92. iterationNode.error = item.error
  93. }
  94. }
  95. const processNonIterationNode = (item: NodeTracing) => {
  96. const { execution_metadata } = item
  97. if (!execution_metadata?.iteration_id) {
  98. if (item.status === 'retry') {
  99. const retryNode = result.find(node => node.node_id === item.node_id)
  100. if (retryNode) {
  101. if (retryNode?.retryDetail)
  102. retryNode.retryDetail.push(item)
  103. else
  104. retryNode.retryDetail = [item]
  105. }
  106. return
  107. }
  108. result.push(item)
  109. return
  110. }
  111. const iterationNode = result.find(node => node.node_id === execution_metadata.iteration_id)
  112. if (!iterationNode || !Array.isArray(iterationNode.details))
  113. return
  114. const { parallel_mode_run_id, iteration_index = 0 } = execution_metadata
  115. if (parallel_mode_run_id)
  116. updateParallelModeGroup(parallel_mode_run_id, item, iterationNode)
  117. else
  118. updateSequentialModeGroup(iteration_index, item, iterationNode)
  119. }
  120. allItems.forEach((item) => {
  121. item.node_type === BlockEnum.Iteration
  122. ? processIterationNode(item)
  123. : processNonIterationNode(item)
  124. })
  125. return result
  126. }, [])
  127. const getTracingList = useCallback(async (appID: string, runID: string) => {
  128. try {
  129. const { data: nodeList } = await fetchTracingList({
  130. url: `/apps/${appID}/workflow-runs/${runID}/node-executions`,
  131. })
  132. setList(formatNodeList(nodeList))
  133. }
  134. catch (err) {
  135. notify({
  136. type: 'error',
  137. message: `${err}`,
  138. })
  139. }
  140. }, [notify])
  141. const getData = async (appID: string, runID: string) => {
  142. setLoading(true)
  143. await getResult(appID, runID)
  144. await getTracingList(appID, runID)
  145. setLoading(false)
  146. }
  147. const switchTab = async (tab: string) => {
  148. setCurrentTab(tab)
  149. if (tab === 'RESULT')
  150. appDetail?.id && await getResult(appDetail.id, runID)
  151. appDetail?.id && await getTracingList(appDetail.id, runID)
  152. }
  153. useEffect(() => {
  154. // fetch data
  155. if (appDetail && runID)
  156. getData(appDetail.id, runID)
  157. }, [appDetail, runID])
  158. const [height, setHeight] = useState(0)
  159. const ref = useRef<HTMLDivElement>(null)
  160. const adjustResultHeight = () => {
  161. if (ref.current)
  162. setHeight(ref.current?.clientHeight - 16 - 16 - 2 - 1)
  163. }
  164. useEffect(() => {
  165. adjustResultHeight()
  166. }, [loading])
  167. const [iterationRunResult, setIterationRunResult] = useState<NodeTracing[][]>([])
  168. const [iterDurationMap, setIterDurationMap] = useState<IterationDurationMap>({})
  169. const [retryRunResult, setRetryRunResult] = useState<NodeTracing[]>([])
  170. const [isShowIterationDetail, {
  171. setTrue: doShowIterationDetail,
  172. setFalse: doHideIterationDetail,
  173. }] = useBoolean(false)
  174. const [isShowRetryDetail, {
  175. setTrue: doShowRetryDetail,
  176. setFalse: doHideRetryDetail,
  177. }] = useBoolean(false)
  178. const handleShowIterationDetail = useCallback((detail: NodeTracing[][], iterDurationMap: IterationDurationMap) => {
  179. setIterationRunResult(detail)
  180. doShowIterationDetail()
  181. setIterDurationMap(iterDurationMap)
  182. }, [doShowIterationDetail, setIterationRunResult, setIterDurationMap])
  183. const handleShowRetryDetail = useCallback((detail: NodeTracing[]) => {
  184. setRetryRunResult(detail)
  185. doShowRetryDetail()
  186. }, [doShowRetryDetail, setRetryRunResult])
  187. if (isShowIterationDetail) {
  188. return (
  189. <div className='grow relative flex flex-col'>
  190. <IterationResultPanel
  191. list={iterationRunResult}
  192. onHide={doHideIterationDetail}
  193. onBack={doHideIterationDetail}
  194. iterDurationMap={iterDurationMap}
  195. />
  196. </div>
  197. )
  198. }
  199. return (
  200. <div className='grow relative flex flex-col'>
  201. {/* tab */}
  202. <div className='shrink-0 flex items-center px-4 border-b-[0.5px] border-divider-subtle'>
  203. {!hideResult && (
  204. <div
  205. className={cn(
  206. 'mr-6 py-3 border-b-2 border-transparent system-sm-semibold-uppercase text-text-tertiary cursor-pointer',
  207. currentTab === 'RESULT' && '!border-util-colors-blue-brand-blue-brand-600 text-text-primary',
  208. )}
  209. onClick={() => switchTab('RESULT')}
  210. >{t('runLog.result')}</div>
  211. )}
  212. <div
  213. className={cn(
  214. 'mr-6 py-3 border-b-2 border-transparent system-sm-semibold-uppercase text-text-tertiary cursor-pointer',
  215. currentTab === 'DETAIL' && '!border-util-colors-blue-brand-blue-brand-600 text-text-primary',
  216. )}
  217. onClick={() => switchTab('DETAIL')}
  218. >{t('runLog.detail')}</div>
  219. <div
  220. className={cn(
  221. 'mr-6 py-3 border-b-2 border-transparent system-sm-semibold-uppercase text-text-tertiary cursor-pointer',
  222. currentTab === 'TRACING' && '!border-util-colors-blue-brand-blue-brand-600 text-text-primary',
  223. )}
  224. onClick={() => switchTab('TRACING')}
  225. >{t('runLog.tracing')}</div>
  226. </div>
  227. {/* panel detail */}
  228. <div ref={ref} className={cn('grow bg-components-panel-bg h-0 overflow-y-auto rounded-b-2xl', currentTab !== 'DETAIL' && '!bg-background-section-burn')}>
  229. {loading && (
  230. <div className='flex h-full items-center justify-center bg-components-panel-bg'>
  231. <Loading />
  232. </div>
  233. )}
  234. {!loading && currentTab === 'RESULT' && runDetail && (
  235. <OutputPanel
  236. outputs={runDetail.outputs}
  237. error={runDetail.error}
  238. height={height}
  239. />
  240. )}
  241. {!loading && currentTab === 'DETAIL' && runDetail && (
  242. <ResultPanel
  243. inputs={runDetail.inputs}
  244. outputs={runDetail.outputs}
  245. status={runDetail.status}
  246. error={runDetail.error}
  247. elapsed_time={runDetail.elapsed_time}
  248. total_tokens={runDetail.total_tokens}
  249. created_at={runDetail.created_at}
  250. created_by={executor}
  251. steps={runDetail.total_steps}
  252. exceptionCounts={runDetail.exceptions_count}
  253. />
  254. )}
  255. {!loading && currentTab === 'TRACING' && !isShowRetryDetail && (
  256. <TracingPanel
  257. className='bg-background-section-burn'
  258. list={list}
  259. onShowIterationDetail={handleShowIterationDetail}
  260. onShowRetryDetail={handleShowRetryDetail}
  261. />
  262. )}
  263. {
  264. !loading && currentTab === 'TRACING' && isShowRetryDetail && (
  265. <RetryResultPanel
  266. list={retryRunResult}
  267. onBack={doHideRetryDetail}
  268. />
  269. )
  270. }
  271. </div>
  272. </div>
  273. )
  274. }
  275. export default RunPanel