You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

list.tsx 38KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030
  1. 'use client'
  2. import type { FC } from 'react'
  3. import React, { useCallback, useEffect, useRef, useState } from 'react'
  4. import useSWR from 'swr'
  5. import {
  6. HandThumbDownIcon,
  7. HandThumbUpIcon,
  8. } from '@heroicons/react/24/outline'
  9. import { RiCloseLine, RiEditFill } from '@remixicon/react'
  10. import { get } from 'lodash-es'
  11. import dayjs from 'dayjs'
  12. import utc from 'dayjs/plugin/utc'
  13. import timezone from 'dayjs/plugin/timezone'
  14. import { createContext, useContext } from 'use-context-selector'
  15. import { useShallow } from 'zustand/react/shallow'
  16. import { useTranslation } from 'react-i18next'
  17. import type { ChatItemInTree } from '../../base/chat/types'
  18. import Indicator from '../../header/indicator'
  19. import VarPanel from './var-panel'
  20. import type { FeedbackFunc, FeedbackType, IChatItem, SubmitAnnotationFunc } from '@/app/components/base/chat/chat/type'
  21. import type { Annotation, ChatConversationGeneralDetail, ChatConversationsResponse, ChatMessage, ChatMessagesRequest, CompletionConversationGeneralDetail, CompletionConversationsResponse, LogAnnotation } from '@/models/log'
  22. import type { App } from '@/types/app'
  23. import ActionButton from '@/app/components/base/action-button'
  24. import Loading from '@/app/components/base/loading'
  25. import Drawer from '@/app/components/base/drawer'
  26. import Chat from '@/app/components/base/chat/chat'
  27. import { ToastContext } from '@/app/components/base/toast'
  28. import { fetchChatConversationDetail, fetchChatMessages, fetchCompletionConversationDetail, updateLogMessageAnnotations, updateLogMessageFeedbacks } from '@/service/log'
  29. import ModelInfo from '@/app/components/app/log/model-info'
  30. import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'
  31. import TextGeneration from '@/app/components/app/text-generate/item'
  32. import { addFileInfos, sortAgentSorts } from '@/app/components/tools/utils'
  33. import MessageLogModal from '@/app/components/base/message-log-modal'
  34. import { useStore as useAppStore } from '@/app/components/app/store'
  35. import { useAppContext } from '@/context/app-context'
  36. import useTimestamp from '@/hooks/use-timestamp'
  37. import Tooltip from '@/app/components/base/tooltip'
  38. import { CopyIcon } from '@/app/components/base/copy-icon'
  39. import { buildChatItemTree, getThreadMessages } from '@/app/components/base/chat/utils'
  40. import { getProcessedFilesFromResponse } from '@/app/components/base/file-uploader/utils'
  41. import cn from '@/utils/classnames'
  42. import { noop } from 'lodash-es'
  43. import PromptLogModal from '../../base/prompt-log-modal'
  44. dayjs.extend(utc)
  45. dayjs.extend(timezone)
  46. type IConversationList = {
  47. logs?: ChatConversationsResponse | CompletionConversationsResponse
  48. appDetail: App
  49. onRefresh: () => void
  50. }
  51. const defaultValue = 'N/A'
  52. type IDrawerContext = {
  53. onClose: () => void
  54. appDetail?: App
  55. }
  56. type StatusCount = {
  57. success: number
  58. failed: number
  59. partial_success: number
  60. }
  61. const DrawerContext = createContext<IDrawerContext>({} as IDrawerContext)
  62. /**
  63. * Icon component with numbers
  64. */
  65. const HandThumbIconWithCount: FC<{ count: number; iconType: 'up' | 'down' }> = ({ count, iconType }) => {
  66. const classname = iconType === 'up' ? 'text-primary-600 bg-primary-50' : 'text-red-600 bg-red-50'
  67. const Icon = iconType === 'up' ? HandThumbUpIcon : HandThumbDownIcon
  68. return <div className={`inline-flex w-fit items-center rounded-md p-1 text-xs ${classname} mr-1 last:mr-0`}>
  69. <Icon className={'mr-0.5 h-3 w-3 rounded-md'} />
  70. {count > 0 ? count : null}
  71. </div>
  72. }
  73. const statusTdRender = (statusCount: StatusCount) => {
  74. if (!statusCount)
  75. return null
  76. if (statusCount.partial_success + statusCount.failed === 0) {
  77. return (
  78. <div className='system-xs-semibold-uppercase inline-flex items-center gap-1'>
  79. <Indicator color={'green'} />
  80. <span className='text-util-colors-green-green-600'>Success</span>
  81. </div>
  82. )
  83. }
  84. else if (statusCount.failed === 0) {
  85. return (
  86. <div className='system-xs-semibold-uppercase inline-flex items-center gap-1'>
  87. <Indicator color={'green'} />
  88. <span className='text-util-colors-green-green-600'>Partial Success</span>
  89. </div>
  90. )
  91. }
  92. else {
  93. return (
  94. <div className='system-xs-semibold-uppercase inline-flex items-center gap-1'>
  95. <Indicator color={'red'} />
  96. <span className='text-util-colors-red-red-600'>{statusCount.failed} {`${statusCount.failed > 1 ? 'Failures' : 'Failure'}`}</span>
  97. </div>
  98. )
  99. }
  100. }
  101. const getFormattedChatList = (messages: ChatMessage[], conversationId: string, timezone: string, format: string) => {
  102. const newChatList: IChatItem[] = []
  103. try {
  104. messages.forEach((item: ChatMessage) => {
  105. const questionFiles = item.message_files?.filter((file: any) => file.belongs_to === 'user') || []
  106. newChatList.push({
  107. id: `question-${item.id}`,
  108. content: item.inputs.query || item.inputs.default_input || item.query, // text generation: item.inputs.query; chat: item.query
  109. isAnswer: false,
  110. message_files: getProcessedFilesFromResponse(questionFiles.map((item: any) => ({ ...item, related_id: item.id }))),
  111. parentMessageId: item.parent_message_id || undefined,
  112. })
  113. const answerFiles = item.message_files?.filter((file: any) => file.belongs_to === 'assistant') || []
  114. newChatList.push({
  115. id: item.id,
  116. content: item.answer,
  117. agent_thoughts: addFileInfos(item.agent_thoughts ? sortAgentSorts(item.agent_thoughts) : item.agent_thoughts, item.message_files),
  118. feedback: item.feedbacks.find(item => item.from_source === 'user'), // user feedback
  119. adminFeedback: item.feedbacks.find(item => item.from_source === 'admin'), // admin feedback
  120. feedbackDisabled: false,
  121. isAnswer: true,
  122. message_files: getProcessedFilesFromResponse(answerFiles.map((item: any) => ({ ...item, related_id: item.id }))),
  123. log: [
  124. ...item.message,
  125. ...(item.message[item.message.length - 1]?.role !== 'assistant'
  126. ? [
  127. {
  128. role: 'assistant',
  129. text: item.answer,
  130. files: item.message_files?.filter((file: any) => file.belongs_to === 'assistant') || [],
  131. },
  132. ]
  133. : []),
  134. ] as IChatItem['log'],
  135. workflow_run_id: item.workflow_run_id,
  136. conversationId,
  137. input: {
  138. inputs: item.inputs,
  139. query: item.query,
  140. },
  141. more: {
  142. time: dayjs.unix(item.created_at).tz(timezone).format(format),
  143. tokens: item.answer_tokens + item.message_tokens,
  144. latency: item.provider_response_latency.toFixed(2),
  145. },
  146. citation: item.metadata?.retriever_resources,
  147. annotation: (() => {
  148. if (item.annotation_hit_history) {
  149. return {
  150. id: item.annotation_hit_history.annotation_id,
  151. authorName: item.annotation_hit_history.annotation_create_account?.name || 'N/A',
  152. created_at: item.annotation_hit_history.created_at,
  153. }
  154. }
  155. if (item.annotation) {
  156. return {
  157. id: item.annotation.id,
  158. authorName: item.annotation.account.name,
  159. logAnnotation: item.annotation,
  160. created_at: 0,
  161. }
  162. }
  163. return undefined
  164. })(),
  165. parentMessageId: `question-${item.id}`,
  166. })
  167. })
  168. return newChatList
  169. }
  170. catch (error) {
  171. console.error('getFormattedChatList processing failed:', error)
  172. throw error
  173. }
  174. }
  175. type IDetailPanel = {
  176. detail: any
  177. onFeedback: FeedbackFunc
  178. onSubmitAnnotation: SubmitAnnotationFunc
  179. }
  180. function DetailPanel({ detail, onFeedback }: IDetailPanel) {
  181. const MIN_ITEMS_FOR_SCROLL_LOADING = 8
  182. const SCROLL_THRESHOLD_PX = 50
  183. const SCROLL_DEBOUNCE_MS = 200
  184. const { userProfile: { timezone } } = useAppContext()
  185. const { formatTime } = useTimestamp()
  186. const { onClose, appDetail } = useContext(DrawerContext)
  187. const { notify } = useContext(ToastContext)
  188. const { currentLogItem, setCurrentLogItem, showMessageLogModal, setShowMessageLogModal, showPromptLogModal, setShowPromptLogModal, currentLogModalActiveTab } = useAppStore(useShallow(state => ({
  189. currentLogItem: state.currentLogItem,
  190. setCurrentLogItem: state.setCurrentLogItem,
  191. showMessageLogModal: state.showMessageLogModal,
  192. setShowMessageLogModal: state.setShowMessageLogModal,
  193. showPromptLogModal: state.showPromptLogModal,
  194. setShowPromptLogModal: state.setShowPromptLogModal,
  195. currentLogModalActiveTab: state.currentLogModalActiveTab,
  196. })))
  197. const { t } = useTranslation()
  198. const [hasMore, setHasMore] = useState(true)
  199. const [varValues, setVarValues] = useState<Record<string, string>>({})
  200. const isLoadingRef = useRef(false)
  201. const [allChatItems, setAllChatItems] = useState<IChatItem[]>([])
  202. const [chatItemTree, setChatItemTree] = useState<ChatItemInTree[]>([])
  203. const [threadChatItems, setThreadChatItems] = useState<IChatItem[]>([])
  204. const fetchData = useCallback(async () => {
  205. if (isLoadingRef.current)
  206. return
  207. try {
  208. isLoadingRef.current = true
  209. if (!hasMore)
  210. return
  211. const params: ChatMessagesRequest = {
  212. conversation_id: detail.id,
  213. limit: 10,
  214. }
  215. // Use the oldest answer item ID for pagination
  216. const answerItems = allChatItems.filter(item => item.isAnswer)
  217. const oldestAnswerItem = answerItems[answerItems.length - 1]
  218. if (oldestAnswerItem?.id)
  219. params.first_id = oldestAnswerItem.id
  220. const messageRes = await fetchChatMessages({
  221. url: `/apps/${appDetail?.id}/chat-messages`,
  222. params,
  223. })
  224. if (messageRes.data.length > 0) {
  225. const varValues = messageRes.data.at(-1)!.inputs
  226. setVarValues(varValues)
  227. }
  228. setHasMore(messageRes.has_more)
  229. const newAllChatItems = [
  230. ...getFormattedChatList(messageRes.data, detail.id, timezone!, t('appLog.dateTimeFormat') as string),
  231. ...allChatItems,
  232. ]
  233. setAllChatItems(newAllChatItems)
  234. let tree = buildChatItemTree(newAllChatItems)
  235. if (messageRes.has_more === false && detail?.model_config?.configs?.introduction) {
  236. tree = [{
  237. id: 'introduction',
  238. isAnswer: true,
  239. isOpeningStatement: true,
  240. content: detail?.model_config?.configs?.introduction ?? 'hello',
  241. feedbackDisabled: true,
  242. children: tree,
  243. }]
  244. }
  245. setChatItemTree(tree)
  246. const lastMessageId = newAllChatItems.length > 0 ? newAllChatItems[newAllChatItems.length - 1].id : undefined
  247. setThreadChatItems(getThreadMessages(tree, lastMessageId))
  248. }
  249. catch (err) {
  250. console.error('fetchData execution failed:', err)
  251. }
  252. finally {
  253. isLoadingRef.current = false
  254. }
  255. }, [allChatItems, detail.id, hasMore, timezone, t, appDetail, detail?.model_config?.configs?.introduction])
  256. const switchSibling = useCallback((siblingMessageId: string) => {
  257. const newThreadChatItems = getThreadMessages(chatItemTree, siblingMessageId)
  258. setThreadChatItems(newThreadChatItems)
  259. }, [chatItemTree])
  260. const handleAnnotationEdited = useCallback((query: string, answer: string, index: number) => {
  261. setAllChatItems(allChatItems.map((item, i) => {
  262. if (i === index - 1) {
  263. return {
  264. ...item,
  265. content: query,
  266. }
  267. }
  268. if (i === index) {
  269. return {
  270. ...item,
  271. annotation: {
  272. ...item.annotation,
  273. logAnnotation: {
  274. ...item.annotation?.logAnnotation,
  275. content: answer,
  276. },
  277. } as any,
  278. }
  279. }
  280. return item
  281. }))
  282. }, [allChatItems])
  283. const handleAnnotationAdded = useCallback((annotationId: string, authorName: string, query: string, answer: string, index: number) => {
  284. setAllChatItems(allChatItems.map((item, i) => {
  285. if (i === index - 1) {
  286. return {
  287. ...item,
  288. content: query,
  289. }
  290. }
  291. if (i === index) {
  292. const answerItem = {
  293. ...item,
  294. content: item.content,
  295. annotation: {
  296. id: annotationId,
  297. authorName,
  298. logAnnotation: {
  299. content: answer,
  300. account: {
  301. id: '',
  302. name: authorName,
  303. email: '',
  304. },
  305. },
  306. } as Annotation,
  307. }
  308. return answerItem
  309. }
  310. return item
  311. }))
  312. }, [allChatItems])
  313. const handleAnnotationRemoved = useCallback(async (index: number): Promise<boolean> => {
  314. const annotation = allChatItems[index]?.annotation
  315. try {
  316. if (annotation?.id) {
  317. const { delAnnotation } = await import('@/service/annotation')
  318. await delAnnotation(appDetail?.id || '', annotation.id)
  319. }
  320. setAllChatItems(allChatItems.map((item, i) => {
  321. if (i === index) {
  322. return {
  323. ...item,
  324. content: item.content,
  325. annotation: undefined,
  326. }
  327. }
  328. return item
  329. }))
  330. notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  331. return true
  332. }
  333. catch {
  334. notify({ type: 'error', message: t('common.actionMsg.modifiedUnsuccessfully') })
  335. return false
  336. }
  337. }, [allChatItems, appDetail?.id, t])
  338. const fetchInitiated = useRef(false)
  339. // Only load initial messages, don't auto-load more
  340. useEffect(() => {
  341. if (appDetail?.id && detail.id && appDetail?.mode !== 'completion' && !fetchInitiated.current) {
  342. // Mark as initialized, but don't auto-load more messages
  343. fetchInitiated.current = true
  344. // Still call fetchData to get initial messages
  345. fetchData()
  346. }
  347. }, [appDetail?.id, detail.id, appDetail?.mode, fetchData])
  348. const [isLoading, setIsLoading] = useState(false)
  349. const loadMoreMessages = useCallback(async () => {
  350. if (isLoading || !hasMore || !appDetail?.id || !detail.id)
  351. return
  352. setIsLoading(true)
  353. try {
  354. const params: ChatMessagesRequest = {
  355. conversation_id: detail.id,
  356. limit: 10,
  357. }
  358. // Use the earliest response item as the first_id
  359. const answerItems = allChatItems.filter(item => item.isAnswer)
  360. const oldestAnswerItem = answerItems[answerItems.length - 1]
  361. if (oldestAnswerItem?.id) {
  362. params.first_id = oldestAnswerItem.id
  363. }
  364. else if (allChatItems.length > 0 && allChatItems[0]?.id) {
  365. const firstId = allChatItems[0].id.replace('question-', '').replace('answer-', '')
  366. params.first_id = firstId
  367. }
  368. const messageRes = await fetchChatMessages({
  369. url: `/apps/${appDetail.id}/chat-messages`,
  370. params,
  371. })
  372. if (!messageRes.data || messageRes.data.length === 0) {
  373. setHasMore(false)
  374. return
  375. }
  376. if (messageRes.data.length > 0) {
  377. const varValues = messageRes.data.at(-1)!.inputs
  378. setVarValues(varValues)
  379. }
  380. setHasMore(messageRes.has_more)
  381. const newItems = getFormattedChatList(
  382. messageRes.data,
  383. detail.id,
  384. timezone!,
  385. t('appLog.dateTimeFormat') as string,
  386. )
  387. // Check for duplicate messages
  388. const existingIds = new Set(allChatItems.map(item => item.id))
  389. const uniqueNewItems = newItems.filter(item => !existingIds.has(item.id))
  390. if (uniqueNewItems.length === 0) {
  391. if (allChatItems.length > 1) {
  392. const nextId = allChatItems[1].id.replace('question-', '').replace('answer-', '')
  393. const retryParams = {
  394. ...params,
  395. first_id: nextId,
  396. }
  397. const retryRes = await fetchChatMessages({
  398. url: `/apps/${appDetail.id}/chat-messages`,
  399. params: retryParams,
  400. })
  401. if (retryRes.data && retryRes.data.length > 0) {
  402. const retryItems = getFormattedChatList(
  403. retryRes.data,
  404. detail.id,
  405. timezone!,
  406. t('appLog.dateTimeFormat') as string,
  407. )
  408. const retryUniqueItems = retryItems.filter(item => !existingIds.has(item.id))
  409. if (retryUniqueItems.length > 0) {
  410. const newAllChatItems = [
  411. ...retryUniqueItems,
  412. ...allChatItems,
  413. ]
  414. setAllChatItems(newAllChatItems)
  415. let tree = buildChatItemTree(newAllChatItems)
  416. if (retryRes.has_more === false && detail?.model_config?.configs?.introduction) {
  417. tree = [{
  418. id: 'introduction',
  419. isAnswer: true,
  420. isOpeningStatement: true,
  421. content: detail?.model_config?.configs?.introduction ?? 'hello',
  422. feedbackDisabled: true,
  423. children: tree,
  424. }]
  425. }
  426. setChatItemTree(tree)
  427. setHasMore(retryRes.has_more)
  428. setThreadChatItems(getThreadMessages(tree, newAllChatItems.at(-1)?.id))
  429. return
  430. }
  431. }
  432. }
  433. }
  434. const newAllChatItems = [
  435. ...uniqueNewItems,
  436. ...allChatItems,
  437. ]
  438. setAllChatItems(newAllChatItems)
  439. let tree = buildChatItemTree(newAllChatItems)
  440. if (messageRes.has_more === false && detail?.model_config?.configs?.introduction) {
  441. tree = [{
  442. id: 'introduction',
  443. isAnswer: true,
  444. isOpeningStatement: true,
  445. content: detail?.model_config?.configs?.introduction ?? 'hello',
  446. feedbackDisabled: true,
  447. children: tree,
  448. }]
  449. }
  450. setChatItemTree(tree)
  451. setThreadChatItems(getThreadMessages(tree, newAllChatItems.at(-1)?.id))
  452. }
  453. catch (error) {
  454. console.error(error)
  455. setHasMore(false)
  456. }
  457. finally {
  458. setIsLoading(false)
  459. }
  460. }, [allChatItems, detail.id, hasMore, isLoading, timezone, t, appDetail])
  461. useEffect(() => {
  462. const scrollableDiv = document.getElementById('scrollableDiv')
  463. const outerDiv = scrollableDiv?.parentElement
  464. const chatContainer = document.querySelector('.mx-1.mb-1.grow.overflow-auto') as HTMLElement
  465. let scrollContainer: HTMLElement | null = null
  466. if (outerDiv && outerDiv.scrollHeight > outerDiv.clientHeight) {
  467. scrollContainer = outerDiv
  468. }
  469. else if (scrollableDiv && scrollableDiv.scrollHeight > scrollableDiv.clientHeight) {
  470. scrollContainer = scrollableDiv
  471. }
  472. else if (chatContainer && chatContainer.scrollHeight > chatContainer.clientHeight) {
  473. scrollContainer = chatContainer
  474. }
  475. else {
  476. const possibleContainers = document.querySelectorAll('.overflow-auto, .overflow-y-auto')
  477. for (let i = 0; i < possibleContainers.length; i++) {
  478. const container = possibleContainers[i] as HTMLElement
  479. if (container.scrollHeight > container.clientHeight) {
  480. scrollContainer = container
  481. break
  482. }
  483. }
  484. }
  485. if (!scrollContainer)
  486. return
  487. let lastLoadTime = 0
  488. const throttleDelay = 200
  489. const handleScroll = () => {
  490. const currentScrollTop = scrollContainer!.scrollTop
  491. const scrollHeight = scrollContainer!.scrollHeight
  492. const clientHeight = scrollContainer!.clientHeight
  493. const distanceFromTop = currentScrollTop
  494. const distanceFromBottom = scrollHeight - currentScrollTop - clientHeight
  495. const now = Date.now()
  496. const isNearTop = distanceFromTop < 30
  497. // eslint-disable-next-line sonarjs/no-unused-vars
  498. const _distanceFromBottom = distanceFromBottom < 30
  499. if (isNearTop && hasMore && !isLoading && (now - lastLoadTime > throttleDelay)) {
  500. lastLoadTime = now
  501. loadMoreMessages()
  502. }
  503. }
  504. scrollContainer.addEventListener('scroll', handleScroll, { passive: true })
  505. const handleWheel = (e: WheelEvent) => {
  506. if (e.deltaY < 0)
  507. handleScroll()
  508. }
  509. scrollContainer.addEventListener('wheel', handleWheel, { passive: true })
  510. return () => {
  511. scrollContainer!.removeEventListener('scroll', handleScroll)
  512. scrollContainer!.removeEventListener('wheel', handleWheel)
  513. }
  514. }, [hasMore, isLoading, loadMoreMessages])
  515. const isChatMode = appDetail?.mode !== 'completion'
  516. const isAdvanced = appDetail?.mode === 'advanced-chat'
  517. const varList = (detail.model_config as any).user_input_form?.map((item: any) => {
  518. const itemContent = item[Object.keys(item)[0]]
  519. return {
  520. label: itemContent.variable,
  521. value: varValues[itemContent.variable] || detail.message?.inputs?.[itemContent.variable],
  522. }
  523. }) || []
  524. const message_files = (!isChatMode && detail.message.message_files && detail.message.message_files.length > 0)
  525. ? detail.message.message_files.map((item: any) => item.url)
  526. : []
  527. const [width, setWidth] = useState(0)
  528. const ref = useRef<HTMLDivElement>(null)
  529. const adjustModalWidth = () => {
  530. if (ref.current)
  531. setWidth(document.body.clientWidth - (ref.current?.clientWidth + 16) - 8)
  532. }
  533. useEffect(() => {
  534. const raf = requestAnimationFrame(adjustModalWidth)
  535. return () => cancelAnimationFrame(raf)
  536. }, [])
  537. // Add scroll listener to ensure loading is triggered
  538. useEffect(() => {
  539. if (threadChatItems.length >= MIN_ITEMS_FOR_SCROLL_LOADING && hasMore) {
  540. const scrollableDiv = document.getElementById('scrollableDiv')
  541. if (scrollableDiv) {
  542. let loadingTimeout: NodeJS.Timeout | null = null
  543. const handleScroll = () => {
  544. const { scrollTop } = scrollableDiv
  545. // Trigger loading when scrolling near the top
  546. if (scrollTop < SCROLL_THRESHOLD_PX && !isLoadingRef.current) {
  547. if (loadingTimeout)
  548. clearTimeout(loadingTimeout)
  549. loadingTimeout = setTimeout(fetchData, SCROLL_DEBOUNCE_MS) // 200ms debounce
  550. }
  551. }
  552. scrollableDiv.addEventListener('scroll', handleScroll)
  553. return () => {
  554. scrollableDiv.removeEventListener('scroll', handleScroll)
  555. if (loadingTimeout)
  556. clearTimeout(loadingTimeout)
  557. }
  558. }
  559. }
  560. }, [threadChatItems.length, hasMore, fetchData])
  561. return (
  562. <div ref={ref} className='flex h-full flex-col rounded-xl border-[0.5px] border-components-panel-border'>
  563. {/* Panel Header */}
  564. <div className='flex shrink-0 items-center gap-2 rounded-t-xl bg-components-panel-bg pb-2 pl-4 pr-3 pt-3'>
  565. <div className='shrink-0'>
  566. <div className='system-xs-semibold-uppercase mb-0.5 text-text-primary'>{isChatMode ? t('appLog.detail.conversationId') : t('appLog.detail.time')}</div>
  567. {isChatMode && (
  568. <div className='system-2xs-regular-uppercase flex items-center text-text-secondary'>
  569. <Tooltip
  570. popupContent={detail.id}
  571. >
  572. <div className='truncate'>{detail.id}</div>
  573. </Tooltip>
  574. <CopyIcon content={detail.id} />
  575. </div>
  576. )}
  577. {!isChatMode && (
  578. <div className='system-2xs-regular-uppercase text-text-secondary'>{formatTime(detail.created_at, t('appLog.dateTimeFormat') as string)}</div>
  579. )}
  580. </div>
  581. <div className='flex grow flex-wrap items-center justify-end gap-y-1'>
  582. {!isAdvanced && <ModelInfo model={detail.model_config.model} />}
  583. </div>
  584. <ActionButton size='l' onClick={onClose}>
  585. <RiCloseLine className='h-4 w-4 text-text-tertiary' />
  586. </ActionButton>
  587. </div>
  588. {/* Panel Body */}
  589. <div className='shrink-0 px-1 pt-1'>
  590. <div className='rounded-t-xl bg-background-section-burn p-3 pb-2'>
  591. {(varList.length > 0 || (!isChatMode && message_files.length > 0)) && (
  592. <VarPanel
  593. varList={varList}
  594. message_files={message_files}
  595. />
  596. )}
  597. </div>
  598. </div>
  599. <div className='mx-1 mb-1 grow overflow-auto rounded-b-xl bg-background-section-burn'>
  600. {!isChatMode
  601. ? <div className="px-6 py-4">
  602. <div className='flex h-[18px] items-center space-x-3'>
  603. <div className='system-xs-semibold-uppercase text-text-tertiary'>{t('appLog.table.header.output')}</div>
  604. <div className='h-[1px] grow' style={{
  605. background: 'linear-gradient(270deg, rgba(243, 244, 246, 0) 0%, rgb(243, 244, 246) 100%)',
  606. }}></div>
  607. </div>
  608. <TextGeneration
  609. className='mt-2'
  610. content={detail.message.answer}
  611. messageId={detail.message.id}
  612. isError={false}
  613. onRetry={noop}
  614. isInstalledApp={false}
  615. supportFeedback
  616. feedback={detail.message.feedbacks.find((item: any) => item.from_source === 'admin')}
  617. onFeedback={feedback => onFeedback(detail.message.id, feedback)}
  618. isShowTextToSpeech
  619. siteInfo={null}
  620. />
  621. </div>
  622. : threadChatItems.length < MIN_ITEMS_FOR_SCROLL_LOADING ? (
  623. <div className="mb-4 pt-4">
  624. <Chat
  625. config={{
  626. appId: appDetail?.id,
  627. text_to_speech: {
  628. enabled: true,
  629. },
  630. questionEditEnable: false,
  631. supportAnnotation: true,
  632. annotation_reply: {
  633. enabled: true,
  634. },
  635. supportFeedback: true,
  636. } as any}
  637. chatList={threadChatItems}
  638. onAnnotationAdded={handleAnnotationAdded}
  639. onAnnotationEdited={handleAnnotationEdited}
  640. onAnnotationRemoved={handleAnnotationRemoved}
  641. onFeedback={onFeedback}
  642. noChatInput
  643. showPromptLog
  644. hideProcessDetail
  645. chatContainerInnerClassName='px-3'
  646. switchSibling={switchSibling}
  647. />
  648. </div>
  649. ) : (
  650. <div
  651. className="py-4"
  652. id="scrollableDiv"
  653. style={{
  654. display: 'flex',
  655. flexDirection: 'column-reverse',
  656. height: '100%',
  657. overflow: 'auto',
  658. }}>
  659. {/* Put the scroll bar always on the bottom */}
  660. <div className="flex w-full flex-col-reverse" style={{ position: 'relative' }}>
  661. {/* Loading state indicator - only shown when loading */}
  662. {hasMore && isLoading && (
  663. <div className="sticky left-0 right-0 top-0 z-10 bg-primary-50/40 py-3 text-center">
  664. <div className='system-xs-regular text-text-tertiary'>
  665. {t('appLog.detail.loading')}...
  666. </div>
  667. </div>
  668. )}
  669. <Chat
  670. config={{
  671. appId: appDetail?.id,
  672. text_to_speech: {
  673. enabled: true,
  674. },
  675. questionEditEnable: false,
  676. supportAnnotation: true,
  677. annotation_reply: {
  678. enabled: true,
  679. },
  680. supportFeedback: true,
  681. } as any}
  682. chatList={threadChatItems}
  683. onAnnotationAdded={handleAnnotationAdded}
  684. onAnnotationEdited={handleAnnotationEdited}
  685. onAnnotationRemoved={handleAnnotationRemoved}
  686. onFeedback={onFeedback}
  687. noChatInput
  688. showPromptLog
  689. hideProcessDetail
  690. chatContainerInnerClassName='px-3'
  691. switchSibling={switchSibling}
  692. />
  693. </div>
  694. </div>
  695. )
  696. }
  697. </div>
  698. {showMessageLogModal && (
  699. <MessageLogModal
  700. width={width}
  701. currentLogItem={currentLogItem}
  702. onCancel={() => {
  703. setCurrentLogItem()
  704. setShowMessageLogModal(false)
  705. }}
  706. defaultTab={currentLogModalActiveTab}
  707. />
  708. )}
  709. {!isChatMode && showPromptLogModal && (
  710. <PromptLogModal
  711. width={width}
  712. currentLogItem={currentLogItem}
  713. onCancel={() => {
  714. setCurrentLogItem()
  715. setShowPromptLogModal(false)
  716. }}
  717. />
  718. )}
  719. </div>
  720. )
  721. }
  722. /**
  723. * Text App Conversation Detail Component
  724. */
  725. const CompletionConversationDetailComp: FC<{ appId?: string; conversationId?: string }> = ({ appId, conversationId }) => {
  726. // Text Generator App Session Details Including Message List
  727. const detailParams = ({ url: `/apps/${appId}/completion-conversations/${conversationId}` })
  728. const { data: conversationDetail, mutate: conversationDetailMutate } = useSWR(() => (appId && conversationId) ? detailParams : null, fetchCompletionConversationDetail)
  729. const { notify } = useContext(ToastContext)
  730. const { t } = useTranslation()
  731. const handleFeedback = async (mid: string, { rating }: FeedbackType): Promise<boolean> => {
  732. try {
  733. await updateLogMessageFeedbacks({ url: `/apps/${appId}/feedbacks`, body: { message_id: mid, rating } })
  734. conversationDetailMutate()
  735. notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  736. return true
  737. }
  738. catch {
  739. notify({ type: 'error', message: t('common.actionMsg.modifiedUnsuccessfully') })
  740. return false
  741. }
  742. }
  743. const handleAnnotation = async (mid: string, value: string): Promise<boolean> => {
  744. try {
  745. await updateLogMessageAnnotations({ url: `/apps/${appId}/annotations`, body: { message_id: mid, content: value } })
  746. conversationDetailMutate()
  747. notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  748. return true
  749. }
  750. catch {
  751. notify({ type: 'error', message: t('common.actionMsg.modifiedUnsuccessfully') })
  752. return false
  753. }
  754. }
  755. if (!conversationDetail)
  756. return null
  757. return <DetailPanel
  758. detail={conversationDetail}
  759. onFeedback={handleFeedback}
  760. onSubmitAnnotation={handleAnnotation}
  761. />
  762. }
  763. /**
  764. * Chat App Conversation Detail Component
  765. */
  766. const ChatConversationDetailComp: FC<{ appId?: string; conversationId?: string }> = ({ appId, conversationId }) => {
  767. const detailParams = { url: `/apps/${appId}/chat-conversations/${conversationId}` }
  768. const { data: conversationDetail } = useSWR(() => (appId && conversationId) ? detailParams : null, fetchChatConversationDetail)
  769. const { notify } = useContext(ToastContext)
  770. const { t } = useTranslation()
  771. const handleFeedback = async (mid: string, { rating }: FeedbackType): Promise<boolean> => {
  772. try {
  773. await updateLogMessageFeedbacks({ url: `/apps/${appId}/feedbacks`, body: { message_id: mid, rating } })
  774. notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  775. return true
  776. }
  777. catch {
  778. notify({ type: 'error', message: t('common.actionMsg.modifiedUnsuccessfully') })
  779. return false
  780. }
  781. }
  782. const handleAnnotation = async (mid: string, value: string): Promise<boolean> => {
  783. try {
  784. await updateLogMessageAnnotations({ url: `/apps/${appId}/annotations`, body: { message_id: mid, content: value } })
  785. notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  786. return true
  787. }
  788. catch {
  789. notify({ type: 'error', message: t('common.actionMsg.modifiedUnsuccessfully') })
  790. return false
  791. }
  792. }
  793. if (!conversationDetail)
  794. return null
  795. return <DetailPanel
  796. detail={conversationDetail}
  797. onFeedback={handleFeedback}
  798. onSubmitAnnotation={handleAnnotation}
  799. />
  800. }
  801. /**
  802. * Conversation list component including basic information
  803. */
  804. const ConversationList: FC<IConversationList> = ({ logs, appDetail, onRefresh }) => {
  805. const { t } = useTranslation()
  806. const { formatTime } = useTimestamp()
  807. const media = useBreakpoints()
  808. const isMobile = media === MediaType.mobile
  809. const [showDrawer, setShowDrawer] = useState<boolean>(false) // Whether to display the chat details drawer
  810. const [currentConversation, setCurrentConversation] = useState<ChatConversationGeneralDetail | CompletionConversationGeneralDetail | undefined>() // Currently selected conversation
  811. const isChatMode = appDetail.mode !== 'completion' // Whether the app is a chat app
  812. const isChatflow = appDetail.mode === 'advanced-chat' // Whether the app is a chatflow app
  813. const { setShowPromptLogModal, setShowAgentLogModal, setShowMessageLogModal } = useAppStore(useShallow(state => ({
  814. setShowPromptLogModal: state.setShowPromptLogModal,
  815. setShowAgentLogModal: state.setShowAgentLogModal,
  816. setShowMessageLogModal: state.setShowMessageLogModal,
  817. })))
  818. // Annotated data needs to be highlighted
  819. const renderTdValue = (value: string | number | null, isEmptyStyle: boolean, isHighlight = false, annotation?: LogAnnotation) => {
  820. return (
  821. <Tooltip
  822. popupContent={
  823. <span className='inline-flex items-center text-xs text-text-tertiary'>
  824. <RiEditFill className='mr-1 h-3 w-3' />{`${t('appLog.detail.annotationTip', { user: annotation?.account?.name })} ${formatTime(annotation?.created_at || dayjs().unix(), 'MM-DD hh:mm A')}`}
  825. </span>
  826. }
  827. popupClassName={(isHighlight && !isChatMode) ? '' : '!hidden'}
  828. >
  829. <div className={cn(isEmptyStyle ? 'text-text-quaternary' : 'text-text-secondary', !isHighlight ? '' : 'bg-orange-100', 'system-sm-regular overflow-hidden text-ellipsis whitespace-nowrap')}>
  830. {value || '-'}
  831. </div>
  832. </Tooltip>
  833. )
  834. }
  835. const onCloseDrawer = () => {
  836. onRefresh()
  837. setShowDrawer(false)
  838. setCurrentConversation(undefined)
  839. setShowPromptLogModal(false)
  840. setShowAgentLogModal(false)
  841. setShowMessageLogModal(false)
  842. }
  843. if (!logs)
  844. return <Loading />
  845. return (
  846. <div className='relative grow overflow-x-auto'>
  847. <table className={cn('mt-2 w-full min-w-[440px] border-collapse border-0')}>
  848. <thead className='system-xs-medium-uppercase text-text-tertiary'>
  849. <tr>
  850. <td className='w-5 whitespace-nowrap rounded-l-lg bg-background-section-burn pl-2 pr-1'></td>
  851. <td className='whitespace-nowrap bg-background-section-burn py-1.5 pl-3'>{isChatMode ? t('appLog.table.header.summary') : t('appLog.table.header.input')}</td>
  852. <td className='whitespace-nowrap bg-background-section-burn py-1.5 pl-3'>{t('appLog.table.header.endUser')}</td>
  853. {isChatflow && <td className='whitespace-nowrap bg-background-section-burn py-1.5 pl-3'>{t('appLog.table.header.status')}</td>}
  854. <td className='whitespace-nowrap bg-background-section-burn py-1.5 pl-3'>{isChatMode ? t('appLog.table.header.messageCount') : t('appLog.table.header.output')}</td>
  855. <td className='whitespace-nowrap bg-background-section-burn py-1.5 pl-3'>{t('appLog.table.header.userRate')}</td>
  856. <td className='whitespace-nowrap bg-background-section-burn py-1.5 pl-3'>{t('appLog.table.header.adminRate')}</td>
  857. <td className='whitespace-nowrap bg-background-section-burn py-1.5 pl-3'>{t('appLog.table.header.updatedTime')}</td>
  858. <td className='whitespace-nowrap rounded-r-lg bg-background-section-burn py-1.5 pl-3'>{t('appLog.table.header.time')}</td>
  859. </tr>
  860. </thead>
  861. <tbody className="system-sm-regular text-text-secondary">
  862. {logs.data.map((log: any) => {
  863. const endUser = log.from_end_user_session_id || log.from_account_name
  864. const leftValue = get(log, isChatMode ? 'name' : 'message.inputs.query') || (!isChatMode ? (get(log, 'message.query') || get(log, 'message.inputs.default_input')) : '') || ''
  865. const rightValue = get(log, isChatMode ? 'message_count' : 'message.answer')
  866. return <tr
  867. key={log.id}
  868. className={cn('cursor-pointer border-b border-divider-subtle hover:bg-background-default-hover', currentConversation?.id !== log.id ? '' : 'bg-background-default-hover')}
  869. onClick={() => {
  870. setShowDrawer(true)
  871. setCurrentConversation(log)
  872. }}>
  873. <td className='h-4'>
  874. {!log.read_at && (
  875. <div className='flex items-center p-3 pr-0.5'>
  876. <span className='inline-block h-1.5 w-1.5 rounded bg-util-colors-blue-blue-500'></span>
  877. </div>
  878. )}
  879. </td>
  880. <td className='w-[160px] p-3 pr-2' style={{ maxWidth: isChatMode ? 300 : 200 }}>
  881. {renderTdValue(leftValue || t('appLog.table.empty.noChat'), !leftValue, isChatMode && log.annotated)}
  882. </td>
  883. <td className='p-3 pr-2'>{renderTdValue(endUser || defaultValue, !endUser)}</td>
  884. {isChatflow && <td className='w-[160px] p-3 pr-2' style={{ maxWidth: isChatMode ? 300 : 200 }}>
  885. {statusTdRender(log.status_count)}
  886. </td>}
  887. <td className='p-3 pr-2' style={{ maxWidth: isChatMode ? 100 : 200 }}>
  888. {renderTdValue(rightValue === 0 ? 0 : (rightValue || t('appLog.table.empty.noOutput')), !rightValue, !isChatMode && !!log.annotation?.content, log.annotation)}
  889. </td>
  890. <td className='p-3 pr-2'>
  891. {(!log.user_feedback_stats.like && !log.user_feedback_stats.dislike)
  892. ? renderTdValue(defaultValue, true)
  893. : <>
  894. {!!log.user_feedback_stats.like && <HandThumbIconWithCount iconType='up' count={log.user_feedback_stats.like} />}
  895. {!!log.user_feedback_stats.dislike && <HandThumbIconWithCount iconType='down' count={log.user_feedback_stats.dislike} />}
  896. </>
  897. }
  898. </td>
  899. <td className='p-3 pr-2'>
  900. {(!log.admin_feedback_stats.like && !log.admin_feedback_stats.dislike)
  901. ? renderTdValue(defaultValue, true)
  902. : <>
  903. {!!log.admin_feedback_stats.like && <HandThumbIconWithCount iconType='up' count={log.admin_feedback_stats.like} />}
  904. {!!log.admin_feedback_stats.dislike && <HandThumbIconWithCount iconType='down' count={log.admin_feedback_stats.dislike} />}
  905. </>
  906. }
  907. </td>
  908. <td className='w-[160px] p-3 pr-2'>{formatTime(log.updated_at, t('appLog.dateTimeFormat') as string)}</td>
  909. <td className='w-[160px] p-3 pr-2'>{formatTime(log.created_at, t('appLog.dateTimeFormat') as string)}</td>
  910. </tr>
  911. })}
  912. </tbody>
  913. </table>
  914. <Drawer
  915. isOpen={showDrawer}
  916. onClose={onCloseDrawer}
  917. mask={isMobile}
  918. footer={null}
  919. panelClassName='mt-16 mx-2 sm:mr-2 mb-4 !p-0 !max-w-[640px] rounded-xl bg-components-panel-bg'
  920. >
  921. <DrawerContext.Provider value={{
  922. onClose: onCloseDrawer,
  923. appDetail,
  924. }}>
  925. {isChatMode
  926. ? <ChatConversationDetailComp appId={appDetail.id} conversationId={currentConversation?.id} />
  927. : <CompletionConversationDetailComp appId={appDetail.id} conversationId={currentConversation?.id} />
  928. }
  929. </DrawerContext.Provider>
  930. </Drawer>
  931. </div>
  932. )
  933. }
  934. export default ConversationList