index.tsx 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809
  1. /* eslint-disable @typescript-eslint/no-use-before-define */
  2. 'use client'
  3. import type { FC } from 'react'
  4. import React, { useEffect, useRef, useState } from 'react'
  5. import cn from 'classnames'
  6. import useSWR from 'swr'
  7. import { useTranslation } from 'react-i18next'
  8. import { useContext } from 'use-context-selector'
  9. import produce from 'immer'
  10. import { useBoolean, useGetState } from 'ahooks'
  11. import AppUnavailable from '../../base/app-unavailable'
  12. import { checkOrSetAccessToken } from '../utils'
  13. import useConversation from './hooks/use-conversation'
  14. import { ToastContext } from '@/app/components/base/toast'
  15. import Sidebar from '@/app/components/share/chat/sidebar'
  16. import ConfigSence from '@/app/components/share/chat/config-scence'
  17. import Header from '@/app/components/share/header'
  18. import {
  19. delConversation,
  20. fetchAppInfo,
  21. fetchAppParams,
  22. fetchChatList,
  23. fetchConversations,
  24. fetchSuggestedQuestions,
  25. generationConversationName,
  26. pinConversation,
  27. sendChatMessage,
  28. stopChatMessageResponding,
  29. unpinConversation,
  30. updateFeedback,
  31. } from '@/service/share'
  32. import type { ConversationItem, SiteInfo } from '@/models/share'
  33. import type { PromptConfig, SuggestedQuestionsAfterAnswerConfig } from '@/models/debug'
  34. import type { Feedbacktype, IChatItem } from '@/app/components/app/chat/type'
  35. import Chat from '@/app/components/app/chat'
  36. import { changeLanguage } from '@/i18n/i18next-config'
  37. import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'
  38. import Loading from '@/app/components/base/loading'
  39. import { replaceStringWithValues } from '@/app/components/app/configuration/prompt-value-panel'
  40. import { userInputsFormToPromptVariables } from '@/utils/model-config'
  41. import type { InstalledApp } from '@/models/explore'
  42. import Confirm from '@/app/components/base/confirm'
  43. import type { VisionFile, VisionSettings } from '@/types/app'
  44. import { Resolution, TransferMethod } from '@/types/app'
  45. import { fetchFileUploadConfig } from '@/service/common'
  46. import type { Annotation as AnnotationType } from '@/models/log'
  47. export type IMainProps = {
  48. isInstalledApp?: boolean
  49. installedAppInfo?: InstalledApp
  50. isSupportPlugin?: boolean
  51. isUniversalChat?: boolean
  52. }
  53. const Main: FC<IMainProps> = ({
  54. isInstalledApp = false,
  55. installedAppInfo,
  56. }) => {
  57. const { t } = useTranslation()
  58. const media = useBreakpoints()
  59. const isMobile = media === MediaType.mobile
  60. /*
  61. * app info
  62. */
  63. const [appUnavailable, setAppUnavailable] = useState<boolean>(false)
  64. const [isUnknwonReason, setIsUnknwonReason] = useState<boolean>(false)
  65. const [appId, setAppId] = useState<string>('')
  66. const [isPublicVersion, setIsPublicVersion] = useState<boolean>(true)
  67. const [siteInfo, setSiteInfo] = useState<SiteInfo | null>()
  68. const [promptConfig, setPromptConfig] = useState<PromptConfig | null>(null)
  69. const [inited, setInited] = useState<boolean>(false)
  70. const [plan, setPlan] = useState<string>('basic') // basic/plus/pro
  71. const [canReplaceLogo, setCanReplaceLogo] = useState<boolean>(false)
  72. const [customConfig, setCustomConfig] = useState<any>(null)
  73. // in mobile, show sidebar by click button
  74. const [isShowSidebar, { setTrue: showSidebar, setFalse: hideSidebar }] = useBoolean(false)
  75. // Can Use metadata(https://beta.nextjs.org/docs/api-reference/metadata) to set title. But it only works in server side client.
  76. useEffect(() => {
  77. if (siteInfo?.title) {
  78. if (canReplaceLogo)
  79. document.title = `${siteInfo.title}`
  80. else
  81. document.title = `${siteInfo.title} - Powered by Dify`
  82. }
  83. }, [siteInfo?.title, canReplaceLogo])
  84. /*
  85. * conversation info
  86. */
  87. const [allConversationList, setAllConversationList] = useState<ConversationItem[]>([])
  88. const [isClearConversationList, { setTrue: clearConversationListTrue, setFalse: clearConversationListFalse }] = useBoolean(false)
  89. const [isClearPinnedConversationList, { setTrue: clearPinnedConversationListTrue, setFalse: clearPinnedConversationListFalse }] = useBoolean(false)
  90. const {
  91. conversationList,
  92. setConversationList,
  93. pinnedConversationList,
  94. setPinnedConversationList,
  95. currConversationId,
  96. getCurrConversationId,
  97. setCurrConversationId,
  98. getConversationIdFromStorage,
  99. isNewConversation,
  100. currConversationInfo,
  101. currInputs,
  102. newConversationInputs,
  103. // existConversationInputs,
  104. resetNewConversationInputs,
  105. setCurrInputs,
  106. setNewConversationInfo,
  107. existConversationInfo,
  108. setExistConversationInfo,
  109. } = useConversation()
  110. const [hasMore, setHasMore] = useState<boolean>(true)
  111. const [hasPinnedMore, setHasPinnedMore] = useState<boolean>(true)
  112. const onMoreLoaded = ({ data: conversations, has_more }: any) => {
  113. setHasMore(has_more)
  114. if (isClearConversationList) {
  115. setConversationList(conversations)
  116. clearConversationListFalse()
  117. }
  118. else {
  119. setConversationList([...conversationList, ...conversations])
  120. }
  121. }
  122. const onPinnedMoreLoaded = ({ data: conversations, has_more }: any) => {
  123. setHasPinnedMore(has_more)
  124. if (isClearPinnedConversationList) {
  125. setPinnedConversationList(conversations)
  126. clearPinnedConversationListFalse()
  127. }
  128. else {
  129. setPinnedConversationList([...pinnedConversationList, ...conversations])
  130. }
  131. }
  132. const [controlUpdateConversationList, setControlUpdateConversationList] = useState(0)
  133. const noticeUpdateList = () => {
  134. setHasMore(true)
  135. clearConversationListTrue()
  136. setHasPinnedMore(true)
  137. clearPinnedConversationListTrue()
  138. setControlUpdateConversationList(Date.now())
  139. }
  140. const handlePin = async (id: string) => {
  141. await pinConversation(isInstalledApp, installedAppInfo?.id, id)
  142. notify({ type: 'success', message: t('common.api.success') })
  143. noticeUpdateList()
  144. }
  145. const handleUnpin = async (id: string) => {
  146. await unpinConversation(isInstalledApp, installedAppInfo?.id, id)
  147. notify({ type: 'success', message: t('common.api.success') })
  148. noticeUpdateList()
  149. }
  150. const [isShowConfirm, { setTrue: showConfirm, setFalse: hideConfirm }] = useBoolean(false)
  151. const [toDeleteConversationId, setToDeleteConversationId] = useState('')
  152. const handleDelete = (id: string) => {
  153. setToDeleteConversationId(id)
  154. hideSidebar() // mobile
  155. showConfirm()
  156. }
  157. const didDelete = async () => {
  158. await delConversation(isInstalledApp, installedAppInfo?.id, toDeleteConversationId)
  159. notify({ type: 'success', message: t('common.api.success') })
  160. hideConfirm()
  161. if (currConversationId === toDeleteConversationId)
  162. handleConversationIdChange('-1')
  163. noticeUpdateList()
  164. }
  165. const [suggestedQuestionsAfterAnswerConfig, setSuggestedQuestionsAfterAnswerConfig] = useState<SuggestedQuestionsAfterAnswerConfig | null>(null)
  166. const [speechToTextConfig, setSpeechToTextConfig] = useState<SuggestedQuestionsAfterAnswerConfig | null>(null)
  167. const [citationConfig, setCitationConfig] = useState<SuggestedQuestionsAfterAnswerConfig | null>(null)
  168. const [conversationIdChangeBecauseOfNew, setConversationIdChangeBecauseOfNew, getConversationIdChangeBecauseOfNew] = useGetState(false)
  169. const [isChatStarted, { setTrue: setChatStarted, setFalse: setChatNotStarted }] = useBoolean(false)
  170. const handleStartChat = (inputs: Record<string, any>) => {
  171. createNewChat()
  172. setConversationIdChangeBecauseOfNew(true)
  173. setCurrInputs(inputs)
  174. setChatStarted()
  175. // parse variables in introduction
  176. setChatList(generateNewChatListWithOpenstatement('', inputs))
  177. }
  178. const hasSetInputs = (() => {
  179. if (!isNewConversation)
  180. return true
  181. return isChatStarted
  182. })()
  183. const conversationName = currConversationInfo?.name || t('share.chat.newChatDefaultName') as string
  184. const conversationIntroduction = currConversationInfo?.introduction || ''
  185. const [controlChatUpdateAllConversation, setControlChatUpdateAllConversation] = useState(0)
  186. useEffect(() => {
  187. (async () => {
  188. if (controlChatUpdateAllConversation && !isNewConversation) {
  189. const { data: allConversations } = await fetchAllConversations() as { data: ConversationItem[]; has_more: boolean }
  190. const item = allConversations.find(item => item.id === currConversationId)
  191. setAllConversationList(allConversations)
  192. if (item) {
  193. setExistConversationInfo({
  194. ...existConversationInfo,
  195. name: item?.name || '',
  196. } as any)
  197. }
  198. }
  199. })()
  200. }, [controlChatUpdateAllConversation])
  201. const handleConversationSwitch = () => {
  202. if (!inited)
  203. return
  204. if (!appId) {
  205. // wait for appId
  206. setTimeout(handleConversationSwitch, 100)
  207. return
  208. }
  209. // update inputs of current conversation
  210. let notSyncToStateIntroduction = ''
  211. let notSyncToStateInputs: Record<string, any> | undefined | null = {}
  212. if (!isNewConversation) {
  213. const item = allConversationList.find(item => item.id === currConversationId)
  214. notSyncToStateInputs = item?.inputs || {}
  215. setCurrInputs(notSyncToStateInputs)
  216. notSyncToStateIntroduction = item?.introduction || ''
  217. setExistConversationInfo({
  218. name: item?.name || '',
  219. introduction: notSyncToStateIntroduction,
  220. })
  221. }
  222. else {
  223. notSyncToStateInputs = newConversationInputs
  224. setCurrInputs(notSyncToStateInputs)
  225. }
  226. // update chat list of current conversation
  227. if (!isNewConversation && !conversationIdChangeBecauseOfNew) {
  228. fetchChatList(currConversationId, isInstalledApp, installedAppInfo?.id).then((res: any) => {
  229. const { data } = res
  230. const newChatList: IChatItem[] = generateNewChatListWithOpenstatement(notSyncToStateIntroduction, notSyncToStateInputs)
  231. data.forEach((item: any) => {
  232. newChatList.push({
  233. id: `question-${item.id}`,
  234. content: item.query,
  235. isAnswer: false,
  236. message_files: item.message_files,
  237. })
  238. newChatList.push({
  239. id: item.id,
  240. content: item.answer,
  241. feedback: item.feedback,
  242. isAnswer: true,
  243. citation: item.retriever_resources,
  244. })
  245. })
  246. setChatList(newChatList)
  247. })
  248. }
  249. if (isNewConversation && isChatStarted)
  250. setChatList(generateNewChatListWithOpenstatement())
  251. setControlFocus(Date.now())
  252. }
  253. useEffect(handleConversationSwitch, [currConversationId, inited])
  254. const handleConversationIdChange = (id: string) => {
  255. if (id === '-1') {
  256. createNewChat()
  257. setConversationIdChangeBecauseOfNew(true)
  258. }
  259. else {
  260. setConversationIdChangeBecauseOfNew(false)
  261. }
  262. // trigger handleConversationSwitch
  263. setCurrConversationId(id, appId)
  264. setIsShowSuggestion(false)
  265. hideSidebar()
  266. }
  267. /*
  268. * chat info. chat is under conversation.
  269. */
  270. const [chatList, setChatList, getChatList] = useGetState<IChatItem[]>([])
  271. const chatListDomRef = useRef<HTMLDivElement>(null)
  272. useEffect(() => {
  273. // scroll to bottom
  274. if (chatListDomRef.current)
  275. chatListDomRef.current.scrollTop = chatListDomRef.current.scrollHeight
  276. }, [chatList, currConversationId])
  277. // user can not edit inputs if user had send message
  278. const canEditInpus = !chatList.some(item => item.isAnswer === false) && isNewConversation
  279. const createNewChat = async () => {
  280. // if new chat is already exist, do not create new chat
  281. abortController?.abort()
  282. setResponsingFalse()
  283. if (conversationList.some(item => item.id === '-1'))
  284. return
  285. setConversationList(produce(conversationList, (draft) => {
  286. draft.unshift({
  287. id: '-1',
  288. name: t('share.chat.newChatDefaultName'),
  289. inputs: newConversationInputs,
  290. introduction: conversationIntroduction,
  291. })
  292. }))
  293. }
  294. // sometime introduction is not applied to state
  295. const generateNewChatListWithOpenstatement = (introduction?: string, inputs?: Record<string, any> | null) => {
  296. let caculatedIntroduction = introduction || conversationIntroduction || ''
  297. const caculatedPromptVariables = inputs || currInputs || null
  298. if (caculatedIntroduction && caculatedPromptVariables)
  299. caculatedIntroduction = replaceStringWithValues(caculatedIntroduction, promptConfig?.prompt_variables || [], caculatedPromptVariables)
  300. // console.log(isPublicVersion)
  301. const openstatement = {
  302. id: `${Date.now()}`,
  303. content: caculatedIntroduction,
  304. isAnswer: true,
  305. feedbackDisabled: true,
  306. isOpeningStatement: true,
  307. }
  308. if (caculatedIntroduction)
  309. return [openstatement]
  310. return []
  311. }
  312. const fetchAllConversations = () => {
  313. return fetchConversations(isInstalledApp, installedAppInfo?.id, undefined, undefined, 100)
  314. }
  315. const fetchInitData = async () => {
  316. if (!isInstalledApp)
  317. await checkOrSetAccessToken()
  318. return Promise.all([isInstalledApp
  319. ? {
  320. app_id: installedAppInfo?.id,
  321. site: {
  322. title: installedAppInfo?.app.name,
  323. icon: installedAppInfo?.app.icon,
  324. icon_background: installedAppInfo?.app.icon_background,
  325. prompt_public: false,
  326. copyright: '',
  327. },
  328. plan: 'basic',
  329. }
  330. : fetchAppInfo(), fetchAllConversations(), fetchAppParams(isInstalledApp, installedAppInfo?.id)])
  331. }
  332. const { data: fileUploadConfigResponse } = useSWR(isInstalledApp ? { url: '/files/upload' } : null, fetchFileUploadConfig)
  333. // init
  334. useEffect(() => {
  335. (async () => {
  336. try {
  337. const [appData, conversationData, appParams]: any = await fetchInitData()
  338. const { app_id: appId, site: siteInfo, plan, can_replace_logo, custom_config }: any = appData
  339. setAppId(appId)
  340. setPlan(plan)
  341. setCanReplaceLogo(can_replace_logo)
  342. setCustomConfig(custom_config)
  343. const tempIsPublicVersion = siteInfo.prompt_public
  344. setIsPublicVersion(tempIsPublicVersion)
  345. const prompt_template = ''
  346. // handle current conversation id
  347. const { data: allConversations } = conversationData as { data: ConversationItem[]; has_more: boolean }
  348. const _conversationId = getConversationIdFromStorage(appId)
  349. const isNotNewConversation = allConversations.some(item => item.id === _conversationId)
  350. setAllConversationList(allConversations)
  351. // fetch new conversation info
  352. const { user_input_form, opening_statement: introduction, suggested_questions_after_answer, speech_to_text, retriever_resource, file_upload, sensitive_word_avoidance }: any = appParams
  353. setVisionConfig({
  354. ...file_upload.image,
  355. image_file_size_limit: appParams?.system_parameters?.image_file_size_limit,
  356. })
  357. const prompt_variables = userInputsFormToPromptVariables(user_input_form)
  358. if (siteInfo.default_language)
  359. changeLanguage(siteInfo.default_language)
  360. setNewConversationInfo({
  361. name: t('share.chat.newChatDefaultName'),
  362. introduction,
  363. })
  364. setSiteInfo(siteInfo as SiteInfo)
  365. setPromptConfig({
  366. prompt_template,
  367. prompt_variables,
  368. } as PromptConfig)
  369. setSuggestedQuestionsAfterAnswerConfig(suggested_questions_after_answer)
  370. setSpeechToTextConfig(speech_to_text)
  371. setCitationConfig(retriever_resource)
  372. // setConversationList(conversations as ConversationItem[])
  373. if (isNotNewConversation)
  374. setCurrConversationId(_conversationId, appId, false)
  375. setInited(true)
  376. }
  377. catch (e: any) {
  378. if (e.status === 404) {
  379. setAppUnavailable(true)
  380. }
  381. else {
  382. setIsUnknwonReason(true)
  383. setAppUnavailable(true)
  384. }
  385. }
  386. })()
  387. }, [])
  388. const [isResponsing, { setTrue: setResponsingTrue, setFalse: setResponsingFalse }] = useBoolean(false)
  389. const [abortController, setAbortController] = useState<AbortController | null>(null)
  390. const { notify } = useContext(ToastContext)
  391. const logError = (message: string) => {
  392. notify({ type: 'error', message })
  393. }
  394. const checkCanSend = () => {
  395. if (currConversationId !== '-1')
  396. return true
  397. const prompt_variables = promptConfig?.prompt_variables
  398. const inputs = currInputs
  399. if (!inputs || !prompt_variables || prompt_variables?.length === 0)
  400. return true
  401. let hasEmptyInput = ''
  402. const requiredVars = prompt_variables?.filter(({ key, name, required }) => {
  403. const res = (!key || !key.trim()) || (!name || !name.trim()) || (required || required === undefined || required === null)
  404. return res
  405. }) || [] // compatible with old version
  406. requiredVars.forEach(({ key, name }) => {
  407. if (hasEmptyInput)
  408. return
  409. if (!inputs?.[key])
  410. hasEmptyInput = name
  411. })
  412. if (hasEmptyInput) {
  413. logError(t('appDebug.errorMessage.valueOfVarRequired', { key: hasEmptyInput }))
  414. return false
  415. }
  416. return !hasEmptyInput
  417. }
  418. const [controlFocus, setControlFocus] = useState(0)
  419. const [isShowSuggestion, setIsShowSuggestion] = useState(false)
  420. const doShowSuggestion = isShowSuggestion && !isResponsing
  421. const [suggestQuestions, setSuggestQuestions] = useState<string[]>([])
  422. const [messageTaskId, setMessageTaskId] = useState('')
  423. const [hasStopResponded, setHasStopResponded, getHasStopResponded] = useGetState(false)
  424. const [isResponsingConIsCurrCon, setIsResponsingConCurrCon, getIsResponsingConIsCurrCon] = useGetState(true)
  425. const [visionConfig, setVisionConfig] = useState<VisionSettings>({
  426. enabled: false,
  427. number_limits: 2,
  428. detail: Resolution.low,
  429. transfer_methods: [TransferMethod.local_file],
  430. })
  431. const handleSend = async (message: string, files?: VisionFile[]) => {
  432. if (isResponsing) {
  433. notify({ type: 'info', message: t('appDebug.errorMessage.waitForResponse') })
  434. return
  435. }
  436. if (files?.find(item => item.transfer_method === TransferMethod.local_file && !item.upload_file_id)) {
  437. notify({ type: 'info', message: t('appDebug.errorMessage.waitForImgUpload') })
  438. return false
  439. }
  440. const data: Record<string, any> = {
  441. inputs: currInputs,
  442. query: message,
  443. conversation_id: isNewConversation ? null : currConversationId,
  444. }
  445. if (visionConfig.enabled && files && files?.length > 0) {
  446. data.files = files.map((item) => {
  447. if (item.transfer_method === TransferMethod.local_file) {
  448. return {
  449. ...item,
  450. url: '',
  451. }
  452. }
  453. return item
  454. })
  455. }
  456. // qustion
  457. const questionId = `question-${Date.now()}`
  458. const questionItem = {
  459. id: questionId,
  460. content: message,
  461. isAnswer: false,
  462. message_files: files,
  463. }
  464. const placeholderAnswerId = `answer-placeholder-${Date.now()}`
  465. const placeholderAnswerItem = {
  466. id: placeholderAnswerId,
  467. content: '',
  468. isAnswer: true,
  469. }
  470. const newList = [...getChatList(), questionItem, placeholderAnswerItem]
  471. setChatList(newList)
  472. // answer
  473. const responseItem: IChatItem = {
  474. id: `${Date.now()}`,
  475. content: '',
  476. isAnswer: true,
  477. }
  478. const prevTempNewConversationId = getCurrConversationId() || '-1'
  479. let tempNewConversationId = prevTempNewConversationId
  480. setHasStopResponded(false)
  481. setResponsingTrue()
  482. setIsShowSuggestion(false)
  483. setIsResponsingConCurrCon(true)
  484. sendChatMessage(data, {
  485. getAbortController: (abortController) => {
  486. setAbortController(abortController)
  487. },
  488. onData: (message: string, isFirstMessage: boolean, { conversationId: newConversationId, messageId, taskId }: any) => {
  489. responseItem.content = responseItem.content + message
  490. responseItem.id = messageId
  491. if (isFirstMessage && newConversationId)
  492. tempNewConversationId = newConversationId
  493. setMessageTaskId(taskId)
  494. // has switched to other conversation
  495. if (prevTempNewConversationId !== getCurrConversationId()) {
  496. setIsResponsingConCurrCon(false)
  497. return
  498. }
  499. // closesure new list is outdated.
  500. const newListWithAnswer = produce(
  501. getChatList().filter(item => item.id !== responseItem.id && item.id !== placeholderAnswerId),
  502. (draft) => {
  503. if (!draft.find(item => item.id === questionId))
  504. draft.push({ ...questionItem })
  505. draft.push({ ...responseItem })
  506. })
  507. setChatList(newListWithAnswer)
  508. },
  509. async onCompleted(hasError?: boolean) {
  510. if (hasError)
  511. return
  512. if (getConversationIdChangeBecauseOfNew()) {
  513. const { data: allConversations }: any = await fetchAllConversations()
  514. const newItem: any = await generationConversationName(isInstalledApp, installedAppInfo?.id, allConversations[0].id)
  515. const newAllConversations = produce(allConversations, (draft: any) => {
  516. draft[0].name = newItem.name
  517. })
  518. setAllConversationList(newAllConversations as any)
  519. noticeUpdateList()
  520. }
  521. setConversationIdChangeBecauseOfNew(false)
  522. resetNewConversationInputs()
  523. setChatNotStarted()
  524. setCurrConversationId(tempNewConversationId, appId, true)
  525. if (getIsResponsingConIsCurrCon() && suggestedQuestionsAfterAnswerConfig?.enabled && !getHasStopResponded()) {
  526. const { data }: any = await fetchSuggestedQuestions(responseItem.id, isInstalledApp, installedAppInfo?.id)
  527. setSuggestQuestions(data)
  528. setIsShowSuggestion(true)
  529. }
  530. setResponsingFalse()
  531. },
  532. onMessageEnd: (messageEnd) => {
  533. if (messageEnd.metadata?.annotation_reply) {
  534. responseItem.id = messageEnd.id
  535. responseItem.annotation = ({
  536. id: messageEnd.metadata.annotation_reply.id,
  537. authorName: messageEnd.metadata.annotation_reply.account.name,
  538. } as AnnotationType)
  539. const newListWithAnswer = produce(
  540. getChatList().filter(item => item.id !== responseItem.id && item.id !== placeholderAnswerId),
  541. (draft) => {
  542. if (!draft.find(item => item.id === questionId))
  543. draft.push({ ...questionItem })
  544. draft.push({
  545. ...responseItem,
  546. })
  547. })
  548. setChatList(newListWithAnswer)
  549. return
  550. }
  551. // not support show citation
  552. // responseItem.citation = messageEnd.retriever_resources
  553. if (!isInstalledApp)
  554. return
  555. const newListWithAnswer = produce(
  556. getChatList().filter(item => item.id !== responseItem.id && item.id !== placeholderAnswerId),
  557. (draft) => {
  558. if (!draft.find(item => item.id === questionId))
  559. draft.push({ ...questionItem })
  560. draft.push({ ...responseItem })
  561. })
  562. setChatList(newListWithAnswer)
  563. },
  564. onMessageReplace: (messageReplace) => {
  565. if (isInstalledApp) {
  566. responseItem.content = messageReplace.answer
  567. }
  568. else {
  569. setChatList(produce(
  570. getChatList(),
  571. (draft) => {
  572. const current = draft.find(item => item.id === messageReplace.id)
  573. if (current)
  574. current.content = messageReplace.answer
  575. },
  576. ))
  577. }
  578. },
  579. onError() {
  580. setResponsingFalse()
  581. // role back placeholder answer
  582. setChatList(produce(getChatList(), (draft) => {
  583. draft.splice(draft.findIndex(item => item.id === placeholderAnswerId), 1)
  584. }))
  585. },
  586. }, isInstalledApp, installedAppInfo?.id)
  587. }
  588. const handleFeedback = async (messageId: string, feedback: Feedbacktype) => {
  589. await updateFeedback({ url: `/messages/${messageId}/feedbacks`, body: { rating: feedback.rating } }, isInstalledApp, installedAppInfo?.id)
  590. const newChatList = chatList.map((item) => {
  591. if (item.id === messageId) {
  592. return {
  593. ...item,
  594. feedback,
  595. }
  596. }
  597. return item
  598. })
  599. setChatList(newChatList)
  600. notify({ type: 'success', message: t('common.api.success') })
  601. }
  602. const renderSidebar = () => {
  603. if (!appId || !siteInfo || !promptConfig)
  604. return null
  605. return (
  606. <Sidebar
  607. list={conversationList}
  608. onListChanged={(list) => {
  609. setConversationList(list)
  610. setControlChatUpdateAllConversation(Date.now())
  611. }}
  612. isClearConversationList={isClearConversationList}
  613. pinnedList={pinnedConversationList}
  614. onPinnedListChanged={(list) => {
  615. setPinnedConversationList(list)
  616. setControlChatUpdateAllConversation(Date.now())
  617. }}
  618. isClearPinnedConversationList={isClearPinnedConversationList}
  619. onMoreLoaded={onMoreLoaded}
  620. onPinnedMoreLoaded={onPinnedMoreLoaded}
  621. isNoMore={!hasMore}
  622. isPinnedNoMore={!hasPinnedMore}
  623. onCurrentIdChange={handleConversationIdChange}
  624. currentId={currConversationId}
  625. copyRight={siteInfo.copyright || siteInfo.title}
  626. isInstalledApp={isInstalledApp}
  627. installedAppId={installedAppInfo?.id}
  628. siteInfo={siteInfo}
  629. onPin={handlePin}
  630. onUnpin={handleUnpin}
  631. controlUpdateList={controlUpdateConversationList}
  632. onDelete={handleDelete}
  633. onStartChat={() => handleConversationIdChange('-1')}
  634. />
  635. )
  636. }
  637. if (appUnavailable)
  638. return <AppUnavailable isUnknwonReason={isUnknwonReason} />
  639. if (!appId || !siteInfo || !promptConfig) {
  640. return <div className='flex h-screen w-full'>
  641. <Loading type='app' />
  642. </div>
  643. }
  644. return (
  645. <div className='bg-gray-100 h-full flex flex-col'>
  646. {!isInstalledApp && (
  647. <Header
  648. title={siteInfo.title}
  649. icon={siteInfo.icon || ''}
  650. icon_background={siteInfo.icon_background}
  651. isMobile={isMobile}
  652. onShowSideBar={showSidebar}
  653. onCreateNewChat={() => handleConversationIdChange('-1')}
  654. />
  655. )}
  656. <div
  657. className={cn(
  658. 'flex rounded-t-2xl bg-white overflow-hidden h-full w-full',
  659. isInstalledApp && 'rounded-b-2xl',
  660. )}
  661. style={isInstalledApp
  662. ? {
  663. boxShadow: '0px 12px 16px -4px rgba(16, 24, 40, 0.08), 0px 4px 6px -2px rgba(16, 24, 40, 0.03)',
  664. }
  665. : {}}
  666. >
  667. {/* sidebar */}
  668. {!isMobile && renderSidebar()}
  669. {isMobile && isShowSidebar && (
  670. <div className='fixed inset-0 z-50'
  671. style={{ backgroundColor: 'rgba(35, 56, 118, 0.2)' }}
  672. onClick={hideSidebar}
  673. >
  674. <div className='inline-block' onClick={e => e.stopPropagation()}>
  675. {renderSidebar()}
  676. </div>
  677. </div>
  678. )}
  679. {/* main */}
  680. <div className={cn(
  681. 'h-full flex-grow flex flex-col overflow-y-auto',
  682. )
  683. }>
  684. <ConfigSence
  685. conversationName={conversationName}
  686. hasSetInputs={hasSetInputs}
  687. isPublicVersion={isPublicVersion}
  688. siteInfo={siteInfo}
  689. promptConfig={promptConfig}
  690. onStartChat={handleStartChat}
  691. canEidtInpus={canEditInpus}
  692. savedInputs={currInputs as Record<string, any>}
  693. onInputsChange={setCurrInputs}
  694. plan={plan}
  695. canReplaceLogo={canReplaceLogo}
  696. customConfig={customConfig}
  697. ></ConfigSence>
  698. {
  699. hasSetInputs && (
  700. <div className={cn(doShowSuggestion ? 'pb-[140px]' : (isResponsing ? 'pb-[113px]' : 'pb-[76px]'), 'relative grow h-[200px] pc:w-[794px] max-w-full mobile:w-full mx-auto mb-3.5 overflow-hidden')}>
  701. <div className='h-full overflow-y-auto' ref={chatListDomRef}>
  702. <Chat
  703. chatList={chatList}
  704. onSend={handleSend}
  705. isHideFeedbackEdit
  706. onFeedback={handleFeedback}
  707. isResponsing={isResponsing}
  708. canStopResponsing={!!messageTaskId && isResponsingConIsCurrCon}
  709. abortResponsing={async () => {
  710. await stopChatMessageResponding(appId, messageTaskId, isInstalledApp, installedAppInfo?.id)
  711. setHasStopResponded(true)
  712. setResponsingFalse()
  713. }}
  714. checkCanSend={checkCanSend}
  715. controlFocus={controlFocus}
  716. isShowSuggestion={doShowSuggestion}
  717. suggestionList={suggestQuestions}
  718. isShowSpeechToText={speechToTextConfig?.enabled}
  719. isShowCitation={citationConfig?.enabled && isInstalledApp}
  720. visionConfig={{
  721. ...visionConfig,
  722. image_file_size_limit: fileUploadConfigResponse ? fileUploadConfigResponse.image_file_size_limit : visionConfig.image_file_size_limit,
  723. }}
  724. />
  725. </div>
  726. </div>)
  727. }
  728. {isShowConfirm && (
  729. <Confirm
  730. title={t('share.chat.deleteConversation.title')}
  731. content={t('share.chat.deleteConversation.content')}
  732. isShow={isShowConfirm}
  733. onClose={hideConfirm}
  734. onConfirm={didDelete}
  735. onCancel={hideConfirm}
  736. />
  737. )}
  738. </div>
  739. </div>
  740. </div>
  741. )
  742. }
  743. export default React.memo(Main)