index.tsx 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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. onShowIterationDetail: (detail: NodeTracing[][]) => void
  25. }
  26. const RunPanel: FC<RunProps> = ({ hideResult, activeTab = 'RESULT', runID, getResultCallback, onShowIterationDetail }) => {
  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. let iterationIndexInfos: {
  62. start: number
  63. end: number
  64. }[] = []
  65. allItems.forEach((item) => {
  66. const { node_type, index, execution_metadata } = item
  67. if (node_type !== BlockEnum.Iteration) {
  68. let isInIteration = false
  69. let isIterationFirstNode = false
  70. iterationIndexInfos.forEach(({ start, end }) => {
  71. if (index >= start && index < end) {
  72. if (index === start)
  73. isIterationFirstNode = true
  74. isInIteration = true
  75. }
  76. })
  77. if (isInIteration) {
  78. const iterationDetails = result[result.length - 1].details!
  79. if (isIterationFirstNode)
  80. iterationDetails!.push([item])
  81. else
  82. iterationDetails[iterationDetails.length - 1].push(item)
  83. return
  84. }
  85. // not in iteration
  86. result.push(item)
  87. return
  88. }
  89. const { steps_boundary } = execution_metadata
  90. iterationIndexInfos = []
  91. steps_boundary.forEach((boundary, index) => {
  92. if (index === 0) {
  93. iterationIndexInfos.push({
  94. start: boundary,
  95. end: 0,
  96. })
  97. }
  98. else if (index === steps_boundary.length - 1) {
  99. iterationIndexInfos[iterationIndexInfos.length - 1].end = boundary
  100. }
  101. else {
  102. iterationIndexInfos[iterationIndexInfos.length - 1].end = boundary
  103. iterationIndexInfos.push({
  104. start: boundary,
  105. end: 0,
  106. })
  107. }
  108. })
  109. result.push({
  110. ...item,
  111. details: [],
  112. })
  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, setHieght] = useState(0)
  148. const ref = useRef<HTMLDivElement>(null)
  149. const adjustResultHeight = () => {
  150. if (ref.current)
  151. setHieght(ref.current?.clientHeight - 16 - 16 - 2 - 1)
  152. }
  153. useEffect(() => {
  154. adjustResultHeight()
  155. }, [loading])
  156. const [iterationRunResult, setIterationRunResult] = useState<NodeTracing[][]>([])
  157. const [isShowIterationDetail, {
  158. setTrue: doShowIterationDetail,
  159. setFalse: doHideIterationDetail,
  160. }] = useBoolean(false)
  161. const handleShowIterationDetail = useCallback((detail: NodeTracing[][]) => {
  162. setIterationRunResult(detail)
  163. doShowIterationDetail()
  164. }, [doShowIterationDetail])
  165. if (isShowIterationDetail) {
  166. return (
  167. <div className='grow relative flex flex-col'>
  168. <IterationResultPanel
  169. list={iterationRunResult}
  170. onHide={doHideIterationDetail}
  171. onBack={doHideIterationDetail}
  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-[rgba(0,0,0,0.05)]'>
  180. {!hideResult && (
  181. <div
  182. className={cn(
  183. 'mr-6 py-3 border-b-2 border-transparent text-[13px] font-semibold leading-[18px] text-gray-400 cursor-pointer',
  184. currentTab === 'RESULT' && '!border-[rgb(21,94,239)] text-gray-700',
  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 text-[13px] font-semibold leading-[18px] text-gray-400 cursor-pointer',
  192. currentTab === 'DETAIL' && '!border-[rgb(21,94,239)] text-gray-700',
  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 text-[13px] font-semibold leading-[18px] text-gray-400 cursor-pointer',
  199. currentTab === 'TRACING' && '!border-[rgb(21,94,239)] text-gray-700',
  200. )}
  201. onClick={() => switchTab('TRACING')}
  202. >{t('runLog.tracing')}</div>
  203. </div>
  204. {/* panel detal */}
  205. <div ref={ref} className={cn('grow bg-white h-0 overflow-y-auto rounded-b-2xl', currentTab !== 'DETAIL' && '!bg-gray-50')}>
  206. {loading && (
  207. <div className='flex h-full items-center justify-center bg-white'>
  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. list={list}
  234. onShowIterationDetail={handleShowIterationDetail}
  235. />
  236. )}
  237. </div>
  238. </div>
  239. )
  240. }
  241. export default RunPanel