list.tsx 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744
  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. XMarkIcon,
  9. } from '@heroicons/react/24/outline'
  10. import { RiEditFill, RiQuestionLine } from '@remixicon/react'
  11. import { get } from 'lodash-es'
  12. import InfiniteScroll from 'react-infinite-scroll-component'
  13. import dayjs from 'dayjs'
  14. import utc from 'dayjs/plugin/utc'
  15. import timezone from 'dayjs/plugin/timezone'
  16. import { createContext, useContext } from 'use-context-selector'
  17. import { useShallow } from 'zustand/react/shallow'
  18. import { useTranslation } from 'react-i18next'
  19. import s from './style.module.css'
  20. import VarPanel from './var-panel'
  21. import cn from '@/utils/classnames'
  22. import type { FeedbackFunc, Feedbacktype, IChatItem, SubmitAnnotationFunc } from '@/app/components/base/chat/chat/type'
  23. import type { Annotation, ChatConversationFullDetailResponse, ChatConversationGeneralDetail, ChatConversationsResponse, ChatMessage, ChatMessagesRequest, CompletionConversationFullDetailResponse, CompletionConversationGeneralDetail, CompletionConversationsResponse, LogAnnotation } from '@/models/log'
  24. import type { App } from '@/types/app'
  25. import Loading from '@/app/components/base/loading'
  26. import Drawer from '@/app/components/base/drawer'
  27. import Popover from '@/app/components/base/popover'
  28. import Chat from '@/app/components/base/chat/chat'
  29. import { ToastContext } from '@/app/components/base/toast'
  30. import { fetchChatConversationDetail, fetchChatMessages, fetchCompletionConversationDetail, updateLogMessageAnnotations, updateLogMessageFeedbacks } from '@/service/log'
  31. import { TONE_LIST } from '@/config'
  32. import ModelIcon from '@/app/components/header/account-setting/model-provider-page/model-icon'
  33. import { useTextGenerationCurrentProviderAndModelAndModelList } from '@/app/components/header/account-setting/model-provider-page/hooks'
  34. import ModelName from '@/app/components/header/account-setting/model-provider-page/model-name'
  35. import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'
  36. import TextGeneration from '@/app/components/app/text-generate/item'
  37. import { addFileInfos, sortAgentSorts } from '@/app/components/tools/utils'
  38. import MessageLogModal from '@/app/components/base/message-log-modal'
  39. import { useStore as useAppStore } from '@/app/components/app/store'
  40. import { useAppContext } from '@/context/app-context'
  41. import useTimestamp from '@/hooks/use-timestamp'
  42. import Tooltip from '@/app/components/base/tooltip'
  43. import { CopyIcon } from '@/app/components/base/copy-icon'
  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. const DrawerContext = createContext<IDrawerContext>({} as IDrawerContext)
  57. /**
  58. * Icon component with numbers
  59. */
  60. const HandThumbIconWithCount: FC<{ count: number; iconType: 'up' | 'down' }> = ({ count, iconType }) => {
  61. const classname = iconType === 'up' ? 'text-primary-600 bg-primary-50' : 'text-red-600 bg-red-50'
  62. const Icon = iconType === 'up' ? HandThumbUpIcon : HandThumbDownIcon
  63. return <div className={`inline-flex items-center w-fit rounded-md p-1 text-xs ${classname} mr-1 last:mr-0`}>
  64. <Icon className={'h-3 w-3 mr-0.5 rounded-md'} />
  65. {count > 0 ? count : null}
  66. </div>
  67. }
  68. const PARAM_MAP = {
  69. temperature: 'Temperature',
  70. top_p: 'Top P',
  71. presence_penalty: 'Presence Penalty',
  72. max_tokens: 'Max Token',
  73. stop: 'Stop',
  74. frequency_penalty: 'Frequency Penalty',
  75. }
  76. // Format interface data for easy display
  77. const getFormattedChatList = (messages: ChatMessage[], conversationId: string, timezone: string, format: string) => {
  78. const newChatList: IChatItem[] = []
  79. messages.forEach((item: ChatMessage) => {
  80. newChatList.push({
  81. id: `question-${item.id}`,
  82. content: item.inputs.query || item.inputs.default_input || item.query, // text generation: item.inputs.query; chat: item.query
  83. isAnswer: false,
  84. message_files: item.message_files?.filter((file: any) => file.belongs_to === 'user') || [],
  85. })
  86. newChatList.push({
  87. id: item.id,
  88. content: item.answer,
  89. agent_thoughts: addFileInfos(item.agent_thoughts ? sortAgentSorts(item.agent_thoughts) : item.agent_thoughts, item.message_files),
  90. feedback: item.feedbacks.find(item => item.from_source === 'user'), // user feedback
  91. adminFeedback: item.feedbacks.find(item => item.from_source === 'admin'), // admin feedback
  92. feedbackDisabled: false,
  93. isAnswer: true,
  94. message_files: item.message_files?.filter((file: any) => file.belongs_to === 'assistant') || [],
  95. log: [
  96. ...item.message,
  97. ...(item.message[item.message.length - 1]?.role !== 'assistant'
  98. ? [
  99. {
  100. role: 'assistant',
  101. text: item.answer,
  102. files: item.message_files?.filter((file: any) => file.belongs_to === 'assistant') || [],
  103. },
  104. ]
  105. : []),
  106. ],
  107. workflow_run_id: item.workflow_run_id,
  108. conversationId,
  109. input: {
  110. inputs: item.inputs,
  111. query: item.query,
  112. },
  113. more: {
  114. time: dayjs.unix(item.created_at).tz(timezone).format(format),
  115. tokens: item.answer_tokens + item.message_tokens,
  116. latency: item.provider_response_latency.toFixed(2),
  117. },
  118. citation: item.metadata?.retriever_resources,
  119. annotation: (() => {
  120. if (item.annotation_hit_history) {
  121. return {
  122. id: item.annotation_hit_history.annotation_id,
  123. authorName: item.annotation_hit_history.annotation_create_account?.name || 'N/A',
  124. created_at: item.annotation_hit_history.created_at,
  125. }
  126. }
  127. if (item.annotation) {
  128. return {
  129. id: item.annotation.id,
  130. authorName: item.annotation.account.name,
  131. logAnnotation: item.annotation,
  132. created_at: 0,
  133. }
  134. }
  135. return undefined
  136. })(),
  137. })
  138. })
  139. return newChatList
  140. }
  141. // const displayedParams = CompletionParams.slice(0, -2)
  142. const validatedParams = ['temperature', 'top_p', 'presence_penalty', 'frequency_penalty']
  143. type IDetailPanel<T> = {
  144. detail: any
  145. onFeedback: FeedbackFunc
  146. onSubmitAnnotation: SubmitAnnotationFunc
  147. }
  148. function DetailPanel<T extends ChatConversationFullDetailResponse | CompletionConversationFullDetailResponse>({ detail, onFeedback }: IDetailPanel<T>) {
  149. const { userProfile: { timezone } } = useAppContext()
  150. const { formatTime } = useTimestamp()
  151. const { onClose, appDetail } = useContext(DrawerContext)
  152. const { currentLogItem, setCurrentLogItem, showMessageLogModal, setShowMessageLogModal, currentLogModalActiveTab } = useAppStore(useShallow(state => ({
  153. currentLogItem: state.currentLogItem,
  154. setCurrentLogItem: state.setCurrentLogItem,
  155. showMessageLogModal: state.showMessageLogModal,
  156. setShowMessageLogModal: state.setShowMessageLogModal,
  157. currentLogModalActiveTab: state.currentLogModalActiveTab,
  158. })))
  159. const { t } = useTranslation()
  160. const [items, setItems] = React.useState<IChatItem[]>([])
  161. const [hasMore, setHasMore] = useState(true)
  162. const [varValues, setVarValues] = useState<Record<string, string>>({})
  163. const fetchData = async () => {
  164. try {
  165. if (!hasMore)
  166. return
  167. const params: ChatMessagesRequest = {
  168. conversation_id: detail.id,
  169. limit: 10,
  170. }
  171. if (items?.[0]?.id)
  172. params.first_id = items?.[0]?.id.replace('question-', '')
  173. const messageRes = await fetchChatMessages({
  174. url: `/apps/${appDetail?.id}/chat-messages`,
  175. params,
  176. })
  177. if (messageRes.data.length > 0) {
  178. const varValues = messageRes.data[0].inputs
  179. setVarValues(varValues)
  180. }
  181. const newItems = [...getFormattedChatList(messageRes.data, detail.id, timezone!, t('appLog.dateTimeFormat') as string), ...items]
  182. if (messageRes.has_more === false && detail?.model_config?.configs?.introduction) {
  183. newItems.unshift({
  184. id: 'introduction',
  185. isAnswer: true,
  186. isOpeningStatement: true,
  187. content: detail?.model_config?.configs?.introduction ?? 'hello',
  188. feedbackDisabled: true,
  189. })
  190. }
  191. setItems(newItems)
  192. setHasMore(messageRes.has_more)
  193. }
  194. catch (err) {
  195. console.error(err)
  196. }
  197. }
  198. const handleAnnotationEdited = useCallback((query: string, answer: string, index: number) => {
  199. setItems(items.map((item, i) => {
  200. if (i === index - 1) {
  201. return {
  202. ...item,
  203. content: query,
  204. }
  205. }
  206. if (i === index) {
  207. return {
  208. ...item,
  209. annotation: {
  210. ...item.annotation,
  211. logAnnotation: {
  212. ...item.annotation?.logAnnotation,
  213. content: answer,
  214. },
  215. } as any,
  216. }
  217. }
  218. return item
  219. }))
  220. }, [items])
  221. const handleAnnotationAdded = useCallback((annotationId: string, authorName: string, query: string, answer: string, index: number) => {
  222. setItems(items.map((item, i) => {
  223. if (i === index - 1) {
  224. return {
  225. ...item,
  226. content: query,
  227. }
  228. }
  229. if (i === index) {
  230. const answerItem = {
  231. ...item,
  232. content: item.content,
  233. annotation: {
  234. id: annotationId,
  235. authorName,
  236. logAnnotation: {
  237. content: answer,
  238. account: {
  239. id: '',
  240. name: authorName,
  241. email: '',
  242. },
  243. },
  244. } as Annotation,
  245. }
  246. return answerItem
  247. }
  248. return item
  249. }))
  250. }, [items])
  251. const handleAnnotationRemoved = useCallback((index: number) => {
  252. setItems(items.map((item, i) => {
  253. if (i === index) {
  254. return {
  255. ...item,
  256. content: item.content,
  257. annotation: undefined,
  258. }
  259. }
  260. return item
  261. }))
  262. }, [items])
  263. useEffect(() => {
  264. if (appDetail?.id && detail.id && appDetail?.mode !== 'completion')
  265. fetchData()
  266. }, [appDetail?.id, detail.id, appDetail?.mode])
  267. const isChatMode = appDetail?.mode !== 'completion'
  268. const isAdvanced = appDetail?.mode === 'advanced-chat'
  269. const targetTone = TONE_LIST.find((item: any) => {
  270. let res = true
  271. validatedParams.forEach((param) => {
  272. res = item.config?.[param] === detail.model_config?.configs?.completion_params?.[param]
  273. })
  274. return res
  275. })?.name ?? 'custom'
  276. const modelName = (detail.model_config as any).model?.name
  277. const provideName = (detail.model_config as any).model?.provider as any
  278. const {
  279. currentModel,
  280. currentProvider,
  281. } = useTextGenerationCurrentProviderAndModelAndModelList(
  282. { provider: provideName, model: modelName },
  283. )
  284. const varList = (detail.model_config as any).user_input_form?.map((item: any) => {
  285. const itemContent = item[Object.keys(item)[0]]
  286. return {
  287. label: itemContent.variable,
  288. value: varValues[itemContent.variable] || detail.message?.inputs?.[itemContent.variable],
  289. }
  290. }) || []
  291. const message_files = (!isChatMode && detail.message.message_files && detail.message.message_files.length > 0)
  292. ? detail.message.message_files.map((item: any) => item.url)
  293. : []
  294. const getParamValue = (param: string) => {
  295. const value = detail?.model_config.model?.completion_params?.[param] || '-'
  296. if (param === 'stop') {
  297. if (Array.isArray(value))
  298. return value.join(',')
  299. else
  300. return '-'
  301. }
  302. return value
  303. }
  304. const [width, setWidth] = useState(0)
  305. const ref = useRef<HTMLDivElement>(null)
  306. const adjustModalWidth = () => {
  307. if (ref.current)
  308. setWidth(document.body.clientWidth - (ref.current?.clientWidth + 16) - 8)
  309. }
  310. useEffect(() => {
  311. adjustModalWidth()
  312. }, [])
  313. return (
  314. <div ref={ref} className='rounded-xl border-[0.5px] border-gray-200 h-full flex flex-col overflow-auto'>
  315. {/* Panel Header */}
  316. <div className='border-b border-gray-100 py-4 px-6 flex items-center justify-between'>
  317. <div>
  318. <div className='text-gray-500 text-[10px] leading-[14px]'>{isChatMode ? t('appLog.detail.conversationId') : t('appLog.detail.time')}</div>
  319. {isChatMode && (
  320. <div className='flex items-center text-gray-700 text-[13px] leading-[18px]'>
  321. <Tooltip
  322. popupContent={detail.id}
  323. >
  324. <div className='max-w-[105px] truncate'>{detail.id}</div>
  325. </Tooltip>
  326. <CopyIcon content={detail.id} />
  327. </div>
  328. )}
  329. {!isChatMode && (
  330. <div className='text-gray-700 text-[13px] leading-[18px]'>{formatTime(detail.created_at, t('appLog.dateTimeFormat') as string)}</div>
  331. )}
  332. </div>
  333. <div className='flex items-center flex-wrap gap-y-1 justify-end'>
  334. {!isAdvanced && (
  335. <>
  336. <div
  337. className={cn('mr-2 flex items-center border h-8 px-2 space-x-2 rounded-lg bg-indigo-25 border-[#2A87F5]')}
  338. >
  339. <ModelIcon
  340. className='!w-5 !h-5'
  341. provider={currentProvider}
  342. modelName={currentModel?.model}
  343. />
  344. <ModelName
  345. modelItem={currentModel!}
  346. showMode
  347. />
  348. </div>
  349. <Popover
  350. position='br'
  351. className='!w-[280px]'
  352. btnClassName='mr-4 !bg-gray-50 !py-1.5 !px-2.5 border-none font-normal'
  353. btnElement={<>
  354. <span className='text-[13px]'>{targetTone}</span>
  355. <RiQuestionLine className='h-4 w-4 text-gray-800 ml-1.5' />
  356. </>}
  357. htmlContent={<div className='w-[280px]'>
  358. <div className='flex justify-between py-2 px-4 font-medium text-sm text-gray-700'>
  359. <span>Tone of responses</span>
  360. <div>{targetTone}</div>
  361. </div>
  362. {['temperature', 'top_p', 'presence_penalty', 'max_tokens', 'stop'].map((param: string, index: number) => {
  363. return <div className='flex justify-between py-2 px-4 bg-gray-50' key={index}>
  364. <span className='text-xs text-gray-700'>{PARAM_MAP[param as keyof typeof PARAM_MAP]}</span>
  365. <span className='text-gray-800 font-medium text-xs'>{getParamValue(param)}</span>
  366. </div>
  367. })}
  368. </div>}
  369. />
  370. </>
  371. )}
  372. <div className='w-6 h-6 rounded-lg flex items-center justify-center hover:cursor-pointer hover:bg-gray-100'>
  373. <XMarkIcon className='w-4 h-4 text-gray-500' onClick={onClose} />
  374. </div>
  375. </div>
  376. </div>
  377. {/* Panel Body */}
  378. {(varList.length > 0 || (!isChatMode && message_files.length > 0)) && (
  379. <div className='px-6 pt-4 pb-2'>
  380. <VarPanel
  381. varList={varList}
  382. message_files={message_files}
  383. />
  384. </div>
  385. )}
  386. {!isChatMode
  387. ? <div className="px-6 py-4">
  388. <div className='flex h-[18px] items-center space-x-3'>
  389. <div className='leading-[18px] text-xs font-semibold text-gray-500 uppercase'>{t('appLog.table.header.output')}</div>
  390. <div className='grow h-[1px]' style={{
  391. background: 'linear-gradient(270deg, rgba(243, 244, 246, 0) 0%, rgb(243, 244, 246) 100%)',
  392. }}></div>
  393. </div>
  394. <TextGeneration
  395. className='mt-2'
  396. content={detail.message.answer}
  397. messageId={detail.message.id}
  398. isError={false}
  399. onRetry={() => { }}
  400. isInstalledApp={false}
  401. supportFeedback
  402. feedback={detail.message.feedbacks.find((item: any) => item.from_source === 'admin')}
  403. onFeedback={feedback => onFeedback(detail.message.id, feedback)}
  404. supportAnnotation
  405. isShowTextToSpeech
  406. appId={appDetail?.id}
  407. varList={varList}
  408. siteInfo={null}
  409. />
  410. </div>
  411. : items.length < 8
  412. ? <div className="pt-4 mb-4">
  413. <Chat
  414. config={{
  415. appId: appDetail?.id,
  416. text_to_speech: {
  417. enabled: true,
  418. },
  419. supportAnnotation: true,
  420. annotation_reply: {
  421. enabled: true,
  422. },
  423. supportFeedback: true,
  424. } as any}
  425. chatList={items}
  426. onAnnotationAdded={handleAnnotationAdded}
  427. onAnnotationEdited={handleAnnotationEdited}
  428. onAnnotationRemoved={handleAnnotationRemoved}
  429. onFeedback={onFeedback}
  430. noChatInput
  431. showPromptLog
  432. hideProcessDetail
  433. chatContainerInnerClassName='px-6'
  434. />
  435. </div>
  436. : <div
  437. className="py-4"
  438. id="scrollableDiv"
  439. style={{
  440. height: 1000, // Specify a value
  441. overflow: 'auto',
  442. display: 'flex',
  443. flexDirection: 'column-reverse',
  444. }}>
  445. {/* Put the scroll bar always on the bottom */}
  446. <InfiniteScroll
  447. scrollableTarget="scrollableDiv"
  448. dataLength={items.length}
  449. next={fetchData}
  450. hasMore={hasMore}
  451. loader={<div className='text-center text-gray-400 text-xs'>{t('appLog.detail.loading')}...</div>}
  452. // endMessage={<div className='text-center'>Nothing more to show</div>}
  453. // below props only if you need pull down functionality
  454. refreshFunction={fetchData}
  455. pullDownToRefresh
  456. pullDownToRefreshThreshold={50}
  457. // pullDownToRefreshContent={
  458. // <div className='text-center'>Pull down to refresh</div>
  459. // }
  460. // releaseToRefreshContent={
  461. // <div className='text-center'>Release to refresh</div>
  462. // }
  463. // To put endMessage and loader to the top.
  464. style={{ display: 'flex', flexDirection: 'column-reverse' }}
  465. inverse={true}
  466. >
  467. <Chat
  468. config={{
  469. appId: appDetail?.id,
  470. text_to_speech: {
  471. enabled: true,
  472. },
  473. supportAnnotation: true,
  474. annotation_reply: {
  475. enabled: true,
  476. },
  477. supportFeedback: true,
  478. } as any}
  479. chatList={items}
  480. onAnnotationAdded={handleAnnotationAdded}
  481. onAnnotationEdited={handleAnnotationEdited}
  482. onAnnotationRemoved={handleAnnotationRemoved}
  483. onFeedback={onFeedback}
  484. noChatInput
  485. showPromptLog
  486. hideProcessDetail
  487. chatContainerInnerClassName='px-6'
  488. />
  489. </InfiniteScroll>
  490. </div>
  491. }
  492. {showMessageLogModal && (
  493. <MessageLogModal
  494. width={width}
  495. currentLogItem={currentLogItem}
  496. onCancel={() => {
  497. setCurrentLogItem()
  498. setShowMessageLogModal(false)
  499. }}
  500. defaultTab={currentLogModalActiveTab}
  501. />
  502. )}
  503. </div>
  504. )
  505. }
  506. /**
  507. * Text App Conversation Detail Component
  508. */
  509. const CompletionConversationDetailComp: FC<{ appId?: string; conversationId?: string }> = ({ appId, conversationId }) => {
  510. // Text Generator App Session Details Including Message List
  511. const detailParams = ({ url: `/apps/${appId}/completion-conversations/${conversationId}` })
  512. const { data: conversationDetail, mutate: conversationDetailMutate } = useSWR(() => (appId && conversationId) ? detailParams : null, fetchCompletionConversationDetail)
  513. const { notify } = useContext(ToastContext)
  514. const { t } = useTranslation()
  515. const handleFeedback = async (mid: string, { rating }: Feedbacktype): Promise<boolean> => {
  516. try {
  517. await updateLogMessageFeedbacks({ url: `/apps/${appId}/feedbacks`, body: { message_id: mid, rating } })
  518. conversationDetailMutate()
  519. notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  520. return true
  521. }
  522. catch (err) {
  523. notify({ type: 'error', message: t('common.actionMsg.modifiedUnsuccessfully') })
  524. return false
  525. }
  526. }
  527. const handleAnnotation = async (mid: string, value: string): Promise<boolean> => {
  528. try {
  529. await updateLogMessageAnnotations({ url: `/apps/${appId}/annotations`, body: { message_id: mid, content: value } })
  530. conversationDetailMutate()
  531. notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  532. return true
  533. }
  534. catch (err) {
  535. notify({ type: 'error', message: t('common.actionMsg.modifiedUnsuccessfully') })
  536. return false
  537. }
  538. }
  539. if (!conversationDetail)
  540. return null
  541. return <DetailPanel<CompletionConversationFullDetailResponse>
  542. detail={conversationDetail}
  543. onFeedback={handleFeedback}
  544. onSubmitAnnotation={handleAnnotation}
  545. />
  546. }
  547. /**
  548. * Chat App Conversation Detail Component
  549. */
  550. const ChatConversationDetailComp: FC<{ appId?: string; conversationId?: string }> = ({ appId, conversationId }) => {
  551. const detailParams = { url: `/apps/${appId}/chat-conversations/${conversationId}` }
  552. const { data: conversationDetail } = useSWR(() => (appId && conversationId) ? detailParams : null, fetchChatConversationDetail)
  553. const { notify } = useContext(ToastContext)
  554. const { t } = useTranslation()
  555. const handleFeedback = async (mid: string, { rating }: Feedbacktype): Promise<boolean> => {
  556. try {
  557. await updateLogMessageFeedbacks({ url: `/apps/${appId}/feedbacks`, body: { message_id: mid, rating } })
  558. notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  559. return true
  560. }
  561. catch (err) {
  562. notify({ type: 'error', message: t('common.actionMsg.modifiedUnsuccessfully') })
  563. return false
  564. }
  565. }
  566. const handleAnnotation = async (mid: string, value: string): Promise<boolean> => {
  567. try {
  568. await updateLogMessageAnnotations({ url: `/apps/${appId}/annotations`, body: { message_id: mid, content: value } })
  569. notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  570. return true
  571. }
  572. catch (err) {
  573. notify({ type: 'error', message: t('common.actionMsg.modifiedUnsuccessfully') })
  574. return false
  575. }
  576. }
  577. if (!conversationDetail)
  578. return null
  579. return <DetailPanel<ChatConversationFullDetailResponse>
  580. detail={conversationDetail}
  581. onFeedback={handleFeedback}
  582. onSubmitAnnotation={handleAnnotation}
  583. />
  584. }
  585. /**
  586. * Conversation list component including basic information
  587. */
  588. const ConversationList: FC<IConversationList> = ({ logs, appDetail, onRefresh }) => {
  589. const { t } = useTranslation()
  590. const { formatTime } = useTimestamp()
  591. const media = useBreakpoints()
  592. const isMobile = media === MediaType.mobile
  593. const [showDrawer, setShowDrawer] = useState<boolean>(false) // Whether to display the chat details drawer
  594. const [currentConversation, setCurrentConversation] = useState<ChatConversationGeneralDetail | CompletionConversationGeneralDetail | undefined>() // Currently selected conversation
  595. const isChatMode = appDetail.mode !== 'completion' // Whether the app is a chat app
  596. // Annotated data needs to be highlighted
  597. const renderTdValue = (value: string | number | null, isEmptyStyle: boolean, isHighlight = false, annotation?: LogAnnotation) => {
  598. return (
  599. <Tooltip
  600. popupContent={
  601. <span className='text-xs text-gray-500 inline-flex items-center'>
  602. <RiEditFill className='w-3 h-3 mr-1' />{`${t('appLog.detail.annotationTip', { user: annotation?.account?.name })} ${formatTime(annotation?.created_at || dayjs().unix(), 'MM-DD hh:mm A')}`}
  603. </span>
  604. }
  605. popupClassName={(isHighlight && !isChatMode) ? '' : '!hidden'}
  606. >
  607. <div className={cn(isEmptyStyle ? 'text-gray-400' : 'text-gray-700', !isHighlight ? '' : 'bg-orange-100', 'text-sm overflow-hidden text-ellipsis whitespace-nowrap')}>
  608. {value || '-'}
  609. </div>
  610. </Tooltip>
  611. )
  612. }
  613. const onCloseDrawer = () => {
  614. onRefresh()
  615. setShowDrawer(false)
  616. setCurrentConversation(undefined)
  617. }
  618. if (!logs)
  619. return <Loading />
  620. return (
  621. <div className='overflow-x-auto'>
  622. <table className={`w-full min-w-[440px] border-collapse border-0 text-sm mt-3 ${s.logTable}`}>
  623. <thead className="h-8 leading-8 border-b border-gray-200 text-gray-500 font-bold">
  624. <tr>
  625. <td className='w-[1.375rem] whitespace-nowrap'></td>
  626. <td className='whitespace-nowrap'>{isChatMode ? t('appLog.table.header.summary') : t('appLog.table.header.input')}</td>
  627. <td className='whitespace-nowrap'>{t('appLog.table.header.endUser')}</td>
  628. <td className='whitespace-nowrap'>{isChatMode ? t('appLog.table.header.messageCount') : t('appLog.table.header.output')}</td>
  629. <td className='whitespace-nowrap'>{t('appLog.table.header.userRate')}</td>
  630. <td className='whitespace-nowrap'>{t('appLog.table.header.adminRate')}</td>
  631. <td className='whitespace-nowrap'>{t('appLog.table.header.updatedTime')}</td>
  632. <td className='whitespace-nowrap'>{t('appLog.table.header.time')}</td>
  633. </tr>
  634. </thead>
  635. <tbody className="text-gray-500">
  636. {logs.data.map((log: any) => {
  637. const endUser = log.from_end_user_session_id || log.from_account_name
  638. const leftValue = get(log, isChatMode ? 'name' : 'message.inputs.query') || (!isChatMode ? (get(log, 'message.query') || get(log, 'message.inputs.default_input')) : '') || ''
  639. const rightValue = get(log, isChatMode ? 'message_count' : 'message.answer')
  640. return <tr
  641. key={log.id}
  642. className={`border-b border-gray-200 h-8 hover:bg-gray-50 cursor-pointer ${currentConversation?.id !== log.id ? '' : 'bg-gray-50'}`}
  643. onClick={() => {
  644. setShowDrawer(true)
  645. setCurrentConversation(log)
  646. }}>
  647. <td className='text-center align-middle'>{!log.read_at && <span className='inline-block bg-[#3F83F8] h-1.5 w-1.5 rounded'></span>}</td>
  648. <td style={{ maxWidth: isChatMode ? 300 : 200 }}>
  649. {renderTdValue(leftValue || t('appLog.table.empty.noChat'), !leftValue, isChatMode && log.annotated)}
  650. </td>
  651. <td>{renderTdValue(endUser || defaultValue, !endUser)}</td>
  652. <td style={{ maxWidth: isChatMode ? 100 : 200 }}>
  653. {renderTdValue(rightValue === 0 ? 0 : (rightValue || t('appLog.table.empty.noOutput')), !rightValue, !isChatMode && !!log.annotation?.content, log.annotation)}
  654. </td>
  655. <td>
  656. {(!log.user_feedback_stats.like && !log.user_feedback_stats.dislike)
  657. ? renderTdValue(defaultValue, true)
  658. : <>
  659. {!!log.user_feedback_stats.like && <HandThumbIconWithCount iconType='up' count={log.user_feedback_stats.like} />}
  660. {!!log.user_feedback_stats.dislike && <HandThumbIconWithCount iconType='down' count={log.user_feedback_stats.dislike} />}
  661. </>
  662. }
  663. </td>
  664. <td>
  665. {(!log.admin_feedback_stats.like && !log.admin_feedback_stats.dislike)
  666. ? renderTdValue(defaultValue, true)
  667. : <>
  668. {!!log.admin_feedback_stats.like && <HandThumbIconWithCount iconType='up' count={log.admin_feedback_stats.like} />}
  669. {!!log.admin_feedback_stats.dislike && <HandThumbIconWithCount iconType='down' count={log.admin_feedback_stats.dislike} />}
  670. </>
  671. }
  672. </td>
  673. <td className='w-[160px]'>{formatTime(log.updated_at, t('appLog.dateTimeFormat') as string)}</td>
  674. <td className='w-[160px]'>{formatTime(log.created_at, t('appLog.dateTimeFormat') as string)}</td>
  675. </tr>
  676. })}
  677. </tbody>
  678. </table>
  679. <Drawer
  680. isOpen={showDrawer}
  681. onClose={onCloseDrawer}
  682. mask={isMobile}
  683. footer={null}
  684. panelClassname='mt-16 mx-2 sm:mr-2 mb-4 !p-0 !max-w-[640px] rounded-xl'
  685. >
  686. <DrawerContext.Provider value={{
  687. onClose: onCloseDrawer,
  688. appDetail,
  689. }}>
  690. {isChatMode
  691. ? <ChatConversationDetailComp appId={appDetail.id} conversationId={currentConversation?.id} />
  692. : <CompletionConversationDetailComp appId={appDetail.id} conversationId={currentConversation?.id} />
  693. }
  694. </DrawerContext.Provider>
  695. </Drawer>
  696. </div>
  697. )
  698. }
  699. export default ConversationList