index.tsx 28 KB

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