index.tsx 29 KB

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