index.tsx 28 KB

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