index.tsx 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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 { 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 [isShowIterationDetail, {
  155. setTrue: doShowIterationDetail,
  156. setFalse: doHideIterationDetail,
  157. }] = useBoolean(false)
  158. const handleShowIterationDetail = useCallback((detail: NodeTracing[][]) => {
  159. setIterationRunResult(detail)
  160. doShowIterationDetail()
  161. }, [doShowIterationDetail])
  162. if (isShowIterationDetail) {
  163. return (
  164. <div className='grow relative flex flex-col'>
  165. <IterationResultPanel
  166. list={iterationRunResult}
  167. onHide={doHideIterationDetail}
  168. onBack={doHideIterationDetail}
  169. />
  170. </div>
  171. )
  172. }
  173. return (
  174. <div className='grow relative flex flex-col'>
  175. {/* tab */}
  176. <div className='shrink-0 flex items-center px-4 border-b-[0.5px] border-divider-subtle'>
  177. {!hideResult && (
  178. <div
  179. className={cn(
  180. 'mr-6 py-3 border-b-2 border-transparent system-sm-semibold-uppercase text-text-tertiary cursor-pointer',
  181. currentTab === 'RESULT' && '!border-util-colors-blue-brand-blue-brand-600 text-text-primary',
  182. )}
  183. onClick={() => switchTab('RESULT')}
  184. >{t('runLog.result')}</div>
  185. )}
  186. <div
  187. className={cn(
  188. 'mr-6 py-3 border-b-2 border-transparent system-sm-semibold-uppercase text-text-tertiary cursor-pointer',
  189. currentTab === 'DETAIL' && '!border-util-colors-blue-brand-blue-brand-600 text-text-primary',
  190. )}
  191. onClick={() => switchTab('DETAIL')}
  192. >{t('runLog.detail')}</div>
  193. <div
  194. className={cn(
  195. 'mr-6 py-3 border-b-2 border-transparent system-sm-semibold-uppercase text-text-tertiary cursor-pointer',
  196. currentTab === 'TRACING' && '!border-util-colors-blue-brand-blue-brand-600 text-text-primary',
  197. )}
  198. onClick={() => switchTab('TRACING')}
  199. >{t('runLog.tracing')}</div>
  200. </div>
  201. {/* panel detail */}
  202. <div ref={ref} className={cn('grow bg-components-panel-bg h-0 overflow-y-auto rounded-b-2xl', currentTab !== 'DETAIL' && '!bg-background-section-burn')}>
  203. {loading && (
  204. <div className='flex h-full items-center justify-center bg-components-panel-bg'>
  205. <Loading />
  206. </div>
  207. )}
  208. {!loading && currentTab === 'RESULT' && runDetail && (
  209. <OutputPanel
  210. outputs={runDetail.outputs}
  211. error={runDetail.error}
  212. height={height}
  213. />
  214. )}
  215. {!loading && currentTab === 'DETAIL' && runDetail && (
  216. <ResultPanel
  217. inputs={runDetail.inputs}
  218. outputs={runDetail.outputs}
  219. status={runDetail.status}
  220. error={runDetail.error}
  221. elapsed_time={runDetail.elapsed_time}
  222. total_tokens={runDetail.total_tokens}
  223. created_at={runDetail.created_at}
  224. created_by={executor}
  225. steps={runDetail.total_steps}
  226. />
  227. )}
  228. {!loading && currentTab === 'TRACING' && (
  229. <TracingPanel
  230. className='bg-background-section-burn'
  231. list={list}
  232. onShowIterationDetail={handleShowIterationDetail}
  233. />
  234. )}
  235. </div>
  236. </div>
  237. )
  238. }
  239. export default RunPanel