index.tsx 8.8 KB

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