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 s from './style.module.css'
  15. import { ToastContext } from '@/app/components/base/toast'
  16. import Sidebar from '@/app/components/share/chat/sidebar'
  17. import ConfigSence from '@/app/components/share/chat/config-scence'
  18. import Header from '@/app/components/share/header'
  19. import {
  20. delConversation,
  21. fetchAppInfo,
  22. fetchAppParams,
  23. fetchChatList,
  24. fetchConversations,
  25. fetchSuggestedQuestions,
  26. generationConversationName,
  27. pinConversation,
  28. sendChatMessage,
  29. stopChatMessageResponding,
  30. unpinConversation,
  31. updateFeedback,
  32. } from '@/service/share'
  33. import type { ConversationItem, SiteInfo } from '@/models/share'
  34. import type { PromptConfig, SuggestedQuestionsAfterAnswerConfig } from '@/models/debug'
  35. import type { Feedbacktype, IChatItem } from '@/app/components/app/chat/type'
  36. import Chat from '@/app/components/app/chat'
  37. import { changeLanguage } from '@/i18n/i18next-config'
  38. import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'
  39. import Loading from '@/app/components/base/loading'
  40. import { replaceStringWithValues } from '@/app/components/app/configuration/prompt-value-panel'
  41. import { userInputsFormToPromptVariables } from '@/utils/model-config'
  42. import type { InstalledApp } from '@/models/explore'
  43. import Confirm from '@/app/components/base/confirm'
  44. import type { VisionFile, VisionSettings } from '@/types/app'
  45. import { Resolution, TransferMethod } from '@/types/app'
  46. import { fetchFileUploadConfig } from '@/service/common'
  47. export type IMainProps = {
  48. isInstalledApp?: boolean
  49. installedAppInfo?: InstalledApp
  50. isSupportPlugin?: boolean
  51. isUniversalChat?: boolean
  52. }
  53. const Main: FC<IMainProps> = ({
  54. isInstalledApp = false,
  55. installedAppInfo,
  56. }) => {
  57. const { t } = useTranslation()
  58. const media = useBreakpoints()
  59. const isMobile = media === MediaType.mobile
  60. /*
  61. * app info
  62. */
  63. const [appUnavailable, setAppUnavailable] = useState<boolean>(false)
  64. const [isUnknwonReason, setIsUnknwonReason] = useState<boolean>(false)
  65. const [appId, setAppId] = useState<string>('')
  66. const [isPublicVersion, setIsPublicVersion] = useState<boolean>(true)
  67. const [siteInfo, setSiteInfo] = useState<SiteInfo | null>()
  68. const [promptConfig, setPromptConfig] = useState<PromptConfig | null>(null)
  69. const [inited, setInited] = useState<boolean>(false)
  70. const [plan, setPlan] = useState<string>('basic') // basic/plus/pro
  71. // 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 (plan !== 'basic')
  77. document.title = `${siteInfo.title}`
  78. else
  79. document.title = `${siteInfo.title} - Powered by Dify`
  80. }
  81. }, [siteInfo?.title, plan])
  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 }: any = appData
  337. setAppId(appId)
  338. setPlan(plan)
  339. const tempIsPublicVersion = siteInfo.prompt_public
  340. setIsPublicVersion(tempIsPublicVersion)
  341. const prompt_template = ''
  342. // handle current conversation id
  343. const { data: allConversations } = conversationData as { data: ConversationItem[]; has_more: boolean }
  344. const _conversationId = getConversationIdFromStorage(appId)
  345. const isNotNewConversation = allConversations.some(item => item.id === _conversationId)
  346. setAllConversationList(allConversations)
  347. // fetch new conversation info
  348. const { user_input_form, opening_statement: introduction, suggested_questions_after_answer, speech_to_text, retriever_resource, file_upload, sensitive_word_avoidance }: any = appParams
  349. setVisionConfig({
  350. ...file_upload.image,
  351. image_file_size_limit: appParams?.system_parameters?.image_file_size_limit,
  352. })
  353. const prompt_variables = userInputsFormToPromptVariables(user_input_form)
  354. if (siteInfo.default_language)
  355. changeLanguage(siteInfo.default_language)
  356. setNewConversationInfo({
  357. name: t('share.chat.newChatDefaultName'),
  358. introduction,
  359. })
  360. setSiteInfo(siteInfo as SiteInfo)
  361. setPromptConfig({
  362. prompt_template,
  363. prompt_variables,
  364. } as PromptConfig)
  365. setSuggestedQuestionsAfterAnswerConfig(suggested_questions_after_answer)
  366. setSpeechToTextConfig(speech_to_text)
  367. setCitationConfig(retriever_resource)
  368. // setConversationList(conversations as ConversationItem[])
  369. if (isNotNewConversation)
  370. setCurrConversationId(_conversationId, appId, false)
  371. setInited(true)
  372. }
  373. catch (e: any) {
  374. if (e.status === 404) {
  375. setAppUnavailable(true)
  376. }
  377. else {
  378. setIsUnknwonReason(true)
  379. setAppUnavailable(true)
  380. }
  381. }
  382. })()
  383. }, [])
  384. const [isResponsing, { setTrue: setResponsingTrue, setFalse: setResponsingFalse }] = useBoolean(false)
  385. const [abortController, setAbortController] = useState<AbortController | null>(null)
  386. const { notify } = useContext(ToastContext)
  387. const logError = (message: string) => {
  388. notify({ type: 'error', message })
  389. }
  390. const checkCanSend = () => {
  391. if (currConversationId !== '-1')
  392. return true
  393. const prompt_variables = promptConfig?.prompt_variables
  394. const inputs = currInputs
  395. if (!inputs || !prompt_variables || prompt_variables?.length === 0)
  396. return true
  397. let hasEmptyInput = ''
  398. const requiredVars = prompt_variables?.filter(({ key, name, required }) => {
  399. const res = (!key || !key.trim()) || (!name || !name.trim()) || (required || required === undefined || required === null)
  400. return res
  401. }) || [] // compatible with old version
  402. requiredVars.forEach(({ key, name }) => {
  403. if (hasEmptyInput)
  404. return
  405. if (!inputs?.[key])
  406. hasEmptyInput = name
  407. })
  408. if (hasEmptyInput) {
  409. logError(t('appDebug.errorMessage.valueOfVarRequired', { key: hasEmptyInput }))
  410. return false
  411. }
  412. return !hasEmptyInput
  413. }
  414. const [controlFocus, setControlFocus] = useState(0)
  415. const [isShowSuggestion, setIsShowSuggestion] = useState(false)
  416. const doShowSuggestion = isShowSuggestion && !isResponsing
  417. const [suggestQuestions, setSuggestQuestions] = useState<string[]>([])
  418. const [messageTaskId, setMessageTaskId] = useState('')
  419. const [hasStopResponded, setHasStopResponded, getHasStopResponded] = useGetState(false)
  420. const [isResponsingConIsCurrCon, setIsResponsingConCurrCon, getIsResponsingConIsCurrCon] = useGetState(true)
  421. const [visionConfig, setVisionConfig] = useState<VisionSettings>({
  422. enabled: false,
  423. number_limits: 2,
  424. detail: Resolution.low,
  425. transfer_methods: [TransferMethod.local_file],
  426. })
  427. const handleSend = async (message: string, files?: VisionFile[]) => {
  428. if (isResponsing) {
  429. notify({ type: 'info', message: t('appDebug.errorMessage.waitForResponse') })
  430. return
  431. }
  432. if (files?.find(item => item.transfer_method === TransferMethod.local_file && !item.upload_file_id)) {
  433. notify({ type: 'info', message: t('appDebug.errorMessage.waitForImgUpload') })
  434. return false
  435. }
  436. const data: Record<string, any> = {
  437. inputs: currInputs,
  438. query: message,
  439. conversation_id: isNewConversation ? null : currConversationId,
  440. }
  441. if (visionConfig.enabled && files && files?.length > 0) {
  442. data.files = files.map((item) => {
  443. if (item.transfer_method === TransferMethod.local_file) {
  444. return {
  445. ...item,
  446. url: '',
  447. }
  448. }
  449. return item
  450. })
  451. }
  452. // qustion
  453. const questionId = `question-${Date.now()}`
  454. const questionItem = {
  455. id: questionId,
  456. content: message,
  457. isAnswer: false,
  458. message_files: files,
  459. }
  460. const placeholderAnswerId = `answer-placeholder-${Date.now()}`
  461. const placeholderAnswerItem = {
  462. id: placeholderAnswerId,
  463. content: '',
  464. isAnswer: true,
  465. }
  466. const newList = [...getChatList(), questionItem, placeholderAnswerItem]
  467. setChatList(newList)
  468. // answer
  469. const responseItem: IChatItem = {
  470. id: `${Date.now()}`,
  471. content: '',
  472. isAnswer: true,
  473. }
  474. const prevTempNewConversationId = getCurrConversationId() || '-1'
  475. let tempNewConversationId = prevTempNewConversationId
  476. setHasStopResponded(false)
  477. setResponsingTrue()
  478. setIsShowSuggestion(false)
  479. setIsResponsingConCurrCon(true)
  480. sendChatMessage(data, {
  481. getAbortController: (abortController) => {
  482. setAbortController(abortController)
  483. },
  484. onData: (message: string, isFirstMessage: boolean, { conversationId: newConversationId, messageId, taskId }: any) => {
  485. responseItem.content = responseItem.content + message
  486. responseItem.id = messageId
  487. if (isFirstMessage && newConversationId)
  488. tempNewConversationId = newConversationId
  489. setMessageTaskId(taskId)
  490. // has switched to other conversation
  491. if (prevTempNewConversationId !== getCurrConversationId()) {
  492. setIsResponsingConCurrCon(false)
  493. return
  494. }
  495. // closesure new list is outdated.
  496. const newListWithAnswer = produce(
  497. getChatList().filter(item => item.id !== responseItem.id && item.id !== placeholderAnswerId),
  498. (draft) => {
  499. if (!draft.find(item => item.id === questionId))
  500. draft.push({ ...questionItem })
  501. draft.push({ ...responseItem })
  502. })
  503. setChatList(newListWithAnswer)
  504. },
  505. async onCompleted(hasError?: boolean) {
  506. if (hasError)
  507. return
  508. if (getConversationIdChangeBecauseOfNew()) {
  509. const { data: allConversations }: any = await fetchAllConversations()
  510. const newItem: any = await generationConversationName(isInstalledApp, installedAppInfo?.id, allConversations[0].id)
  511. const newAllConversations = produce(allConversations, (draft: any) => {
  512. draft[0].name = newItem.name
  513. })
  514. setAllConversationList(newAllConversations as any)
  515. noticeUpdateList()
  516. }
  517. setConversationIdChangeBecauseOfNew(false)
  518. resetNewConversationInputs()
  519. setChatNotStarted()
  520. setCurrConversationId(tempNewConversationId, appId, true)
  521. if (getIsResponsingConIsCurrCon() && suggestedQuestionsAfterAnswerConfig?.enabled && !getHasStopResponded()) {
  522. const { data }: any = await fetchSuggestedQuestions(responseItem.id, isInstalledApp, installedAppInfo?.id)
  523. setSuggestQuestions(data)
  524. setIsShowSuggestion(true)
  525. }
  526. setResponsingFalse()
  527. },
  528. onMessageEnd: isInstalledApp
  529. ? (messageEnd) => {
  530. if (!isInstalledApp)
  531. return
  532. responseItem.citation = messageEnd.retriever_resources
  533. const newListWithAnswer = produce(
  534. getChatList().filter(item => item.id !== responseItem.id && item.id !== placeholderAnswerId),
  535. (draft) => {
  536. if (!draft.find(item => item.id === questionId))
  537. draft.push({ ...questionItem })
  538. draft.push({ ...responseItem })
  539. })
  540. setChatList(newListWithAnswer)
  541. }
  542. : undefined,
  543. onMessageReplace: (messageReplace) => {
  544. if (isInstalledApp) {
  545. responseItem.content = messageReplace.answer
  546. }
  547. else {
  548. setChatList(produce(
  549. getChatList(),
  550. (draft) => {
  551. const current = draft.find(item => item.id === messageReplace.id)
  552. if (current)
  553. current.content = messageReplace.answer
  554. },
  555. ))
  556. }
  557. },
  558. onError() {
  559. setResponsingFalse()
  560. // role back placeholder answer
  561. setChatList(produce(getChatList(), (draft) => {
  562. draft.splice(draft.findIndex(item => item.id === placeholderAnswerId), 1)
  563. }))
  564. },
  565. }, isInstalledApp, installedAppInfo?.id)
  566. }
  567. const handleFeedback = async (messageId: string, feedback: Feedbacktype) => {
  568. await updateFeedback({ url: `/messages/${messageId}/feedbacks`, body: { rating: feedback.rating } }, isInstalledApp, installedAppInfo?.id)
  569. const newChatList = chatList.map((item) => {
  570. if (item.id === messageId) {
  571. return {
  572. ...item,
  573. feedback,
  574. }
  575. }
  576. return item
  577. })
  578. setChatList(newChatList)
  579. notify({ type: 'success', message: t('common.api.success') })
  580. }
  581. const renderSidebar = () => {
  582. if (!appId || !siteInfo || !promptConfig)
  583. return null
  584. return (
  585. <Sidebar
  586. list={conversationList}
  587. onListChanged={(list) => {
  588. setConversationList(list)
  589. setControlChatUpdateAllConversation(Date.now())
  590. }}
  591. isClearConversationList={isClearConversationList}
  592. pinnedList={pinnedConversationList}
  593. onPinnedListChanged={(list) => {
  594. setPinnedConversationList(list)
  595. setControlChatUpdateAllConversation(Date.now())
  596. }}
  597. isClearPinnedConversationList={isClearPinnedConversationList}
  598. onMoreLoaded={onMoreLoaded}
  599. onPinnedMoreLoaded={onPinnedMoreLoaded}
  600. isNoMore={!hasMore}
  601. isPinnedNoMore={!hasPinnedMore}
  602. onCurrentIdChange={handleConversationIdChange}
  603. currentId={currConversationId}
  604. copyRight={siteInfo.copyright || siteInfo.title}
  605. isInstalledApp={isInstalledApp}
  606. installedAppId={installedAppInfo?.id}
  607. siteInfo={siteInfo}
  608. onPin={handlePin}
  609. onUnpin={handleUnpin}
  610. controlUpdateList={controlUpdateConversationList}
  611. onDelete={handleDelete}
  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'>
  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 ? s.installedApp : '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)