index.tsx 9.0 KB

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