index.tsx 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  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 { useTranslation } from 'react-i18next'
  7. import { useContext } from 'use-context-selector'
  8. import produce from 'immer'
  9. import { useBoolean, useGetState } from 'ahooks'
  10. import { checkOrSetAccessToken } from '../utils'
  11. import AppUnavailable from '../../base/app-unavailable'
  12. import useConversation from './hooks/use-conversation'
  13. import { ToastContext } from '@/app/components/base/toast'
  14. import ConfigScene from '@/app/components/share/chatbot/config-scence'
  15. import Header from '@/app/components/share/header'
  16. import { fetchAppInfo, fetchAppParams, fetchChatList, fetchConversations, fetchSuggestedQuestions, generationConversationName, sendChatMessage, stopChatMessageResponding, updateFeedback } from '@/service/share'
  17. import type { ConversationItem, SiteInfo } from '@/models/share'
  18. import type { PromptConfig, SuggestedQuestionsAfterAnswerConfig } from '@/models/debug'
  19. import type { Feedbacktype, IChatItem } from '@/app/components/app/chat/type'
  20. import Chat from '@/app/components/app/chat'
  21. import { changeLanguage } from '@/i18n/i18next-config'
  22. import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'
  23. import Loading from '@/app/components/base/loading'
  24. import { replaceStringWithValues } from '@/app/components/app/configuration/prompt-value-panel'
  25. import { userInputsFormToPromptVariables } from '@/utils/model-config'
  26. import type { InstalledApp } from '@/models/explore'
  27. import { AlertTriangle } from '@/app/components/base/icons/src/vender/solid/alertsAndFeedback'
  28. import LogoHeader from '@/app/components/base/logo/logo-embeded-chat-header'
  29. import LogoAvatar from '@/app/components/base/logo/logo-embeded-chat-avatar'
  30. import type { VisionFile, VisionSettings } from '@/types/app'
  31. import { Resolution, TransferMethod } from '@/types/app'
  32. export type IMainProps = {
  33. isInstalledApp?: boolean
  34. installedAppInfo?: InstalledApp
  35. }
  36. const Main: FC<IMainProps> = ({
  37. isInstalledApp = false,
  38. installedAppInfo,
  39. }) => {
  40. const { t } = useTranslation()
  41. const media = useBreakpoints()
  42. const isMobile = media === MediaType.mobile
  43. /*
  44. * app info
  45. */
  46. const [appUnavailable, setAppUnavailable] = useState<boolean>(false)
  47. const [isUnknwonReason, setIsUnknwonReason] = useState<boolean>(false)
  48. const [appId, setAppId] = useState<string>('')
  49. const [isPublicVersion, setIsPublicVersion] = useState<boolean>(true)
  50. const [siteInfo, setSiteInfo] = useState<SiteInfo | null>()
  51. const [promptConfig, setPromptConfig] = useState<PromptConfig | null>(null)
  52. const [inited, setInited] = useState<boolean>(false)
  53. const [plan, setPlan] = useState<string>('basic') // basic/plus/pro
  54. const [canReplaceLogo, setCanReplaceLogo] = useState<boolean>(false)
  55. const [customConfig, setCustomConfig] = useState<any>(null)
  56. // Can Use metadata(https://beta.nextjs.org/docs/api-reference/metadata) to set title. But it only works in server side client.
  57. useEffect(() => {
  58. if (siteInfo?.title) {
  59. if (canReplaceLogo)
  60. document.title = `${siteInfo.title}`
  61. else
  62. document.title = `${siteInfo.title} - Powered by Dify`
  63. }
  64. }, [siteInfo?.title, canReplaceLogo])
  65. /*
  66. * conversation info
  67. */
  68. const [allConversationList, setAllConversationList] = useState<ConversationItem[]>([])
  69. const [isClearConversationList, { setTrue: clearConversationListTrue, setFalse: clearConversationListFalse }] = useBoolean(false)
  70. const [isClearPinnedConversationList, { setTrue: clearPinnedConversationListTrue, setFalse: clearPinnedConversationListFalse }] = useBoolean(false)
  71. const {
  72. conversationList,
  73. setConversationList,
  74. pinnedConversationList,
  75. setPinnedConversationList,
  76. currConversationId,
  77. setCurrConversationId,
  78. getConversationIdFromStorage,
  79. isNewConversation,
  80. currConversationInfo,
  81. currInputs,
  82. newConversationInputs,
  83. // existConversationInputs,
  84. resetNewConversationInputs,
  85. setCurrInputs,
  86. setNewConversationInfo,
  87. setExistConversationInfo,
  88. } = useConversation()
  89. const [hasMore, setHasMore] = useState<boolean>(true)
  90. const [hasPinnedMore, setHasPinnedMore] = useState<boolean>(true)
  91. const onMoreLoaded = ({ data: conversations, has_more }: any) => {
  92. setHasMore(has_more)
  93. if (isClearConversationList) {
  94. setConversationList(conversations)
  95. clearConversationListFalse()
  96. }
  97. else {
  98. setConversationList([...conversationList, ...conversations])
  99. }
  100. }
  101. const onPinnedMoreLoaded = ({ data: conversations, has_more }: any) => {
  102. setHasPinnedMore(has_more)
  103. if (isClearPinnedConversationList) {
  104. setPinnedConversationList(conversations)
  105. clearPinnedConversationListFalse()
  106. }
  107. else {
  108. setPinnedConversationList([...pinnedConversationList, ...conversations])
  109. }
  110. }
  111. const [controlUpdateConversationList, setControlUpdateConversationList] = useState(0)
  112. const noticeUpdateList = () => {
  113. setHasMore(true)
  114. clearConversationListTrue()
  115. setHasPinnedMore(true)
  116. clearPinnedConversationListTrue()
  117. setControlUpdateConversationList(Date.now())
  118. }
  119. const [suggestedQuestionsAfterAnswerConfig, setSuggestedQuestionsAfterAnswerConfig] = useState<SuggestedQuestionsAfterAnswerConfig | null>(null)
  120. const [speechToTextConfig, setSpeechToTextConfig] = useState<SuggestedQuestionsAfterAnswerConfig | null>(null)
  121. const [textToSpeechConfig, setTextToSpeechConfig] = useState<SuggestedQuestionsAfterAnswerConfig | null>(null)
  122. const [citationConfig, setCitationConfig] = useState<SuggestedQuestionsAfterAnswerConfig | null>(null)
  123. const [conversationIdChangeBecauseOfNew, setConversationIdChangeBecauseOfNew, getConversationIdChangeBecauseOfNew] = useGetState(false)
  124. const [isChatStarted, { setTrue: setChatStarted, setFalse: setChatNotStarted }] = useBoolean(false)
  125. const handleStartChat = (inputs: Record<string, any>) => {
  126. createNewChat()
  127. setConversationIdChangeBecauseOfNew(true)
  128. setCurrInputs(inputs)
  129. setChatStarted()
  130. // parse variables in introduction
  131. setChatList(generateNewChatListWithOpenstatement('', inputs))
  132. }
  133. const hasSetInputs = (() => {
  134. if (!isNewConversation)
  135. return true
  136. return isChatStarted
  137. })()
  138. // const conversationName = currConversationInfo?.name || t('share.chat.newChatDefaultName') as string
  139. const conversationIntroduction = currConversationInfo?.introduction || ''
  140. const handleConversationSwitch = () => {
  141. if (!inited)
  142. return
  143. if (!appId) {
  144. // wait for appId
  145. setTimeout(handleConversationSwitch, 100)
  146. return
  147. }
  148. // update inputs of current conversation
  149. let notSyncToStateIntroduction = ''
  150. let notSyncToStateInputs: Record<string, any> | undefined | null = {}
  151. if (!isNewConversation) {
  152. const item = allConversationList.find(item => item.id === currConversationId)
  153. notSyncToStateInputs = item?.inputs || {}
  154. setCurrInputs(notSyncToStateInputs)
  155. notSyncToStateIntroduction = item?.introduction || ''
  156. setExistConversationInfo({
  157. name: item?.name || '',
  158. introduction: notSyncToStateIntroduction,
  159. })
  160. }
  161. else {
  162. notSyncToStateInputs = newConversationInputs
  163. setCurrInputs(notSyncToStateInputs)
  164. }
  165. // update chat list of current conversation
  166. if (!isNewConversation && !conversationIdChangeBecauseOfNew && !isResponsing) {
  167. fetchChatList(currConversationId, isInstalledApp, installedAppInfo?.id).then((res: any) => {
  168. const { data } = res
  169. const newChatList: IChatItem[] = generateNewChatListWithOpenstatement(notSyncToStateIntroduction, notSyncToStateInputs)
  170. data.forEach((item: any) => {
  171. newChatList.push({
  172. id: `question-${item.id}`,
  173. content: item.query,
  174. isAnswer: false,
  175. message_files: item.message_files,
  176. })
  177. newChatList.push({
  178. id: item.id,
  179. content: item.answer,
  180. feedback: item.feedback,
  181. isAnswer: true,
  182. citation: item.retriever_resources,
  183. })
  184. })
  185. setChatList(newChatList)
  186. })
  187. }
  188. if (isNewConversation && isChatStarted)
  189. setChatList(generateNewChatListWithOpenstatement())
  190. setControlFocus(Date.now())
  191. }
  192. useEffect(handleConversationSwitch, [currConversationId, inited])
  193. /*
  194. * chat info. chat is under conversation.
  195. */
  196. const [chatList, setChatList, getChatList] = useGetState<IChatItem[]>([])
  197. const chatListDomRef = useRef<HTMLDivElement>(null)
  198. useEffect(() => {
  199. // scroll to bottom
  200. if (chatListDomRef.current)
  201. chatListDomRef.current.scrollTop = chatListDomRef.current.scrollHeight
  202. }, [chatList, currConversationId])
  203. // user can not edit inputs if user had send message
  204. const canEditInputs = !chatList.some(item => item.isAnswer === false) && isNewConversation
  205. const createNewChat = async () => {
  206. // if new chat is already exist, do not create new chat
  207. abortController?.abort()
  208. setResponsingFalse()
  209. if (conversationList.some(item => item.id === '-1'))
  210. return
  211. setConversationList(produce(conversationList, (draft) => {
  212. draft.unshift({
  213. id: '-1',
  214. name: t('share.chat.newChatDefaultName'),
  215. inputs: newConversationInputs,
  216. introduction: conversationIntroduction,
  217. })
  218. }))
  219. }
  220. // sometime introduction is not applied to state
  221. const generateNewChatListWithOpenstatement = (introduction?: string, inputs?: Record<string, any> | null) => {
  222. let caculatedIntroduction = introduction || conversationIntroduction || ''
  223. const caculatedPromptVariables = inputs || currInputs || null
  224. if (caculatedIntroduction && caculatedPromptVariables)
  225. caculatedIntroduction = replaceStringWithValues(caculatedIntroduction, promptConfig?.prompt_variables || [], caculatedPromptVariables)
  226. const openstatement = {
  227. id: `${Date.now()}`,
  228. content: caculatedIntroduction,
  229. isAnswer: true,
  230. feedbackDisabled: true,
  231. isOpeningStatement: isPublicVersion,
  232. }
  233. if (caculatedIntroduction)
  234. return [openstatement]
  235. return []
  236. }
  237. const fetchAllConversations = () => {
  238. return fetchConversations(isInstalledApp, installedAppInfo?.id, undefined, undefined, 100)
  239. }
  240. const fetchInitData = async () => {
  241. if (!isInstalledApp)
  242. await checkOrSetAccessToken()
  243. return Promise.all([isInstalledApp
  244. ? {
  245. app_id: installedAppInfo?.id,
  246. site: {
  247. title: installedAppInfo?.app.name,
  248. prompt_public: false,
  249. copyright: '',
  250. },
  251. plan: 'basic',
  252. }
  253. : fetchAppInfo(), fetchAllConversations(), fetchAppParams(isInstalledApp, installedAppInfo?.id)])
  254. }
  255. // init
  256. useEffect(() => {
  257. (async () => {
  258. try {
  259. const [appData, conversationData, appParams]: any = await fetchInitData()
  260. const { app_id: appId, site: siteInfo, plan, can_replace_logo, custom_config }: any = appData
  261. setAppId(appId)
  262. setPlan(plan)
  263. setCanReplaceLogo(can_replace_logo)
  264. setCustomConfig(custom_config)
  265. const tempIsPublicVersion = siteInfo.prompt_public
  266. setIsPublicVersion(tempIsPublicVersion)
  267. const prompt_template = ''
  268. // handle current conversation id
  269. const { data: allConversations } = conversationData as { data: ConversationItem[]; has_more: boolean }
  270. const _conversationId = getConversationIdFromStorage(appId)
  271. const isNotNewConversation = allConversations.some(item => item.id === _conversationId)
  272. setAllConversationList(allConversations)
  273. // fetch new conversation info
  274. const { user_input_form, opening_statement: introduction, suggested_questions_after_answer, speech_to_text, text_to_speech, retriever_resource, file_upload, sensitive_word_avoidance }: any = appParams
  275. setVisionConfig({
  276. ...file_upload.image,
  277. image_file_size_limit: appParams?.system_parameters?.image_file_size_limit,
  278. })
  279. const prompt_variables = userInputsFormToPromptVariables(user_input_form)
  280. if (siteInfo.default_language)
  281. changeLanguage(siteInfo.default_language)
  282. setNewConversationInfo({
  283. name: t('share.chat.newChatDefaultName'),
  284. introduction,
  285. })
  286. setSiteInfo(siteInfo as SiteInfo)
  287. setPromptConfig({
  288. prompt_template,
  289. prompt_variables,
  290. } as PromptConfig)
  291. setSuggestedQuestionsAfterAnswerConfig(suggested_questions_after_answer)
  292. setSpeechToTextConfig(speech_to_text)
  293. setTextToSpeechConfig(text_to_speech)
  294. setCitationConfig(retriever_resource)
  295. // setConversationList(conversations as ConversationItem[])
  296. if (isNotNewConversation)
  297. setCurrConversationId(_conversationId, appId, false)
  298. setInited(true)
  299. }
  300. catch (e: any) {
  301. if (e.status === 404) {
  302. setAppUnavailable(true)
  303. }
  304. else {
  305. setIsUnknwonReason(true)
  306. setAppUnavailable(true)
  307. }
  308. }
  309. })()
  310. }, [])
  311. const [isResponsing, { setTrue: setResponsingTrue, setFalse: setResponsingFalse }] = useBoolean(false)
  312. const [abortController, setAbortController] = useState<AbortController | null>(null)
  313. const { notify } = useContext(ToastContext)
  314. const logError = (message: string) => {
  315. notify({ type: 'error', message })
  316. }
  317. const checkCanSend = () => {
  318. if (currConversationId !== '-1')
  319. return true
  320. const prompt_variables = promptConfig?.prompt_variables
  321. const inputs = currInputs
  322. if (!inputs || !prompt_variables || prompt_variables?.length === 0)
  323. return true
  324. let hasEmptyInput = ''
  325. const requiredVars = prompt_variables?.filter(({ key, name, required }) => {
  326. const res = (!key || !key.trim()) || (!name || !name.trim()) || (required || required === undefined || required === null)
  327. return res
  328. }) || [] // compatible with old version
  329. requiredVars.forEach(({ key, name }) => {
  330. if (hasEmptyInput)
  331. return
  332. if (!inputs?.[key])
  333. hasEmptyInput = name
  334. })
  335. if (hasEmptyInput) {
  336. logError(t('appDebug.errorMessage.valueOfVarRequired', { key: hasEmptyInput }))
  337. return false
  338. }
  339. return !hasEmptyInput
  340. }
  341. const [controlFocus, setControlFocus] = useState(0)
  342. const [isShowSuggestion, setIsShowSuggestion] = useState(false)
  343. const doShowSuggestion = isShowSuggestion && !isResponsing
  344. const [suggestQuestions, setSuggestQuestions] = useState<string[]>([])
  345. const [messageTaskId, setMessageTaskId] = useState('')
  346. const [hasStopResponded, setHasStopResponded, getHasStopResponded] = useGetState(false)
  347. const [shouldReload, setShouldReload] = useState(false)
  348. const [userQuery, setUserQuery] = useState('')
  349. const [visionConfig, setVisionConfig] = useState<VisionSettings>({
  350. enabled: false,
  351. number_limits: 2,
  352. detail: Resolution.low,
  353. transfer_methods: [TransferMethod.local_file],
  354. })
  355. const handleSend = async (message: string, files?: VisionFile[]) => {
  356. if (isResponsing) {
  357. notify({ type: 'info', message: t('appDebug.errorMessage.waitForResponse') })
  358. return
  359. }
  360. if (files?.find(item => item.transfer_method === TransferMethod.local_file && !item.upload_file_id)) {
  361. notify({ type: 'info', message: t('appDebug.errorMessage.waitForImgUpload') })
  362. return false
  363. }
  364. const data: Record<string, any> = {
  365. inputs: currInputs,
  366. query: message,
  367. conversation_id: isNewConversation ? null : currConversationId,
  368. }
  369. if (visionConfig.enabled && files && files?.length > 0) {
  370. data.files = files.map((item) => {
  371. if (item.transfer_method === TransferMethod.local_file) {
  372. return {
  373. ...item,
  374. url: '',
  375. }
  376. }
  377. return item
  378. })
  379. }
  380. // qustion
  381. const questionId = `question-${Date.now()}`
  382. const questionItem = {
  383. id: questionId,
  384. content: message,
  385. isAnswer: false,
  386. message_files: files,
  387. }
  388. const placeholderAnswerId = `answer-placeholder-${Date.now()}`
  389. const placeholderAnswerItem = {
  390. id: placeholderAnswerId,
  391. content: '',
  392. isAnswer: true,
  393. }
  394. const newList = [...getChatList(), questionItem, placeholderAnswerItem]
  395. setChatList(newList)
  396. // answer
  397. const responseItem: IChatItem = {
  398. id: `${Date.now()}`,
  399. content: '',
  400. isAnswer: true,
  401. }
  402. let tempNewConversationId = ''
  403. setHasStopResponded(false)
  404. setResponsingTrue()
  405. setIsShowSuggestion(false)
  406. sendChatMessage(data, {
  407. getAbortController: (abortController) => {
  408. setAbortController(abortController)
  409. },
  410. onData: (message: string, isFirstMessage: boolean, { conversationId: newConversationId, messageId, taskId }: any) => {
  411. responseItem.content = responseItem.content + message
  412. responseItem.id = messageId
  413. if (isFirstMessage && newConversationId)
  414. tempNewConversationId = newConversationId
  415. setMessageTaskId(taskId)
  416. // closesure new list is outdated.
  417. const newListWithAnswer = produce(
  418. getChatList().filter(item => item.id !== responseItem.id && item.id !== placeholderAnswerId),
  419. (draft) => {
  420. if (!draft.find(item => item.id === questionId))
  421. draft.push({ ...questionItem })
  422. draft.push({ ...responseItem })
  423. })
  424. setChatList(newListWithAnswer)
  425. },
  426. async onCompleted(hasError?: boolean) {
  427. if (hasError)
  428. return
  429. if (getConversationIdChangeBecauseOfNew()) {
  430. const { data: allConversations }: any = await fetchAllConversations()
  431. const newItem: any = await generationConversationName(isInstalledApp, installedAppInfo?.id, allConversations[0].id)
  432. const newAllConversations = produce(allConversations, (draft: any) => {
  433. draft[0].name = newItem.name
  434. })
  435. setAllConversationList(newAllConversations as any)
  436. noticeUpdateList()
  437. }
  438. setConversationIdChangeBecauseOfNew(false)
  439. resetNewConversationInputs()
  440. setChatNotStarted()
  441. setCurrConversationId(tempNewConversationId, appId, true)
  442. if (suggestedQuestionsAfterAnswerConfig?.enabled && !getHasStopResponded()) {
  443. const { data }: any = await fetchSuggestedQuestions(responseItem.id, isInstalledApp, installedAppInfo?.id)
  444. setSuggestQuestions(data)
  445. setIsShowSuggestion(true)
  446. }
  447. setResponsingFalse()
  448. },
  449. onMessageReplace: (messageReplace) => {
  450. setChatList(produce(
  451. getChatList(),
  452. (draft) => {
  453. const current = draft.find(item => item.id === messageReplace.id)
  454. if (current)
  455. current.content = messageReplace.answer
  456. },
  457. ))
  458. },
  459. onError(errorMessage, errorCode) {
  460. if (['provider_not_initialize', 'completion_request_error'].includes(errorCode as string))
  461. setShouldReload(true)
  462. setResponsingFalse()
  463. // role back placeholder answer
  464. setChatList(produce(getChatList(), (draft) => {
  465. draft.splice(draft.findIndex(item => item.id === placeholderAnswerId), 1)
  466. }))
  467. },
  468. }, isInstalledApp, installedAppInfo?.id)
  469. }
  470. const handleFeedback = async (messageId: string, feedback: Feedbacktype) => {
  471. await updateFeedback({ url: `/messages/${messageId}/feedbacks`, body: { rating: feedback.rating } }, isInstalledApp, installedAppInfo?.id)
  472. const newChatList = chatList.map((item) => {
  473. if (item.id === messageId) {
  474. return {
  475. ...item,
  476. feedback,
  477. }
  478. }
  479. return item
  480. })
  481. setChatList(newChatList)
  482. notify({ type: 'success', message: t('common.api.success') })
  483. }
  484. const handleReload = () => {
  485. setCurrConversationId('-1', appId, false)
  486. setChatNotStarted()
  487. setShouldReload(false)
  488. createNewChat()
  489. }
  490. const handleConversationIdChange = (id: string) => {
  491. if (id === '-1') {
  492. createNewChat()
  493. setConversationIdChangeBecauseOfNew(true)
  494. }
  495. else {
  496. setConversationIdChangeBecauseOfNew(false)
  497. }
  498. // trigger handleConversationSwitch
  499. setCurrConversationId(id, appId)
  500. setIsShowSuggestion(false)
  501. }
  502. const difyIcon = (
  503. <LogoHeader />
  504. )
  505. if (appUnavailable)
  506. return <AppUnavailable isUnknwonReason={isUnknwonReason} />
  507. if (!appId || !siteInfo || !promptConfig) {
  508. return <div className='flex h-screen w-full'>
  509. <Loading type='app' />
  510. </div>
  511. }
  512. return (
  513. <div>
  514. <Header
  515. title={siteInfo.title}
  516. icon=''
  517. customerIcon={difyIcon}
  518. icon_background={siteInfo.icon_background}
  519. isEmbedScene={true}
  520. isMobile={isMobile}
  521. onCreateNewChat={() => handleConversationIdChange('-1')}
  522. />
  523. <div className={'flex bg-white overflow-hidden'}>
  524. <div className={cn(
  525. isInstalledApp ? 'h-full' : 'h-[calc(100vh_-_3rem)]',
  526. 'flex-grow flex flex-col overflow-y-auto',
  527. )
  528. }>
  529. <ConfigScene
  530. // conversationName={conversationName}
  531. hasSetInputs={hasSetInputs}
  532. isPublicVersion={isPublicVersion}
  533. siteInfo={siteInfo}
  534. promptConfig={promptConfig}
  535. onStartChat={handleStartChat}
  536. canEditInputs={canEditInputs}
  537. savedInputs={currInputs as Record<string, any>}
  538. onInputsChange={setCurrInputs}
  539. plan={plan}
  540. canReplaceLogo={canReplaceLogo}
  541. customConfig={customConfig}
  542. ></ConfigScene>
  543. {
  544. shouldReload && (
  545. <div className='flex items-center justify-between mb-5 px-4 py-2 bg-[#FEF0C7]'>
  546. <div className='flex items-center text-xs font-medium text-[#DC6803]'>
  547. <AlertTriangle className='mr-2 w-4 h-4' />
  548. {t('share.chat.temporarySystemIssue')}
  549. </div>
  550. <div
  551. className='flex items-center px-3 h-7 bg-white shadow-xs rounded-md text-xs font-medium text-gray-700 cursor-pointer'
  552. onClick={handleReload}
  553. >
  554. {t('share.chat.tryToSolve')}
  555. </div>
  556. </div>
  557. )
  558. }
  559. {
  560. hasSetInputs && (
  561. <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')}>
  562. <div className='h-full overflow-y-auto' ref={chatListDomRef}>
  563. <Chat
  564. chatList={chatList}
  565. query={userQuery}
  566. onQueryChange={setUserQuery}
  567. onSend={handleSend}
  568. isHideFeedbackEdit
  569. onFeedback={handleFeedback}
  570. isResponsing={isResponsing}
  571. canStopResponsing={!!messageTaskId}
  572. abortResponsing={async () => {
  573. await stopChatMessageResponding(appId, messageTaskId, isInstalledApp, installedAppInfo?.id)
  574. setHasStopResponded(true)
  575. setResponsingFalse()
  576. }}
  577. checkCanSend={checkCanSend}
  578. controlFocus={controlFocus}
  579. isShowSuggestion={doShowSuggestion}
  580. suggestionList={suggestQuestions}
  581. displayScene='web'
  582. isShowSpeechToText={speechToTextConfig?.enabled}
  583. isShowTextToSpeech={textToSpeechConfig?.enabled}
  584. isShowCitation={citationConfig?.enabled && isInstalledApp}
  585. answerIcon={<LogoAvatar className='relative shrink-0' />}
  586. visionConfig={visionConfig}
  587. />
  588. </div>
  589. </div>)
  590. }
  591. {/* {isShowConfirm && (
  592. <Confirm
  593. title={t('share.chat.deleteConversation.title')}
  594. content={t('share.chat.deleteConversation.content')}
  595. isShow={isShowConfirm}
  596. onClose={hideConfirm}
  597. onConfirm={didDelete}
  598. onCancel={hideConfirm}
  599. />
  600. )} */}
  601. </div>
  602. </div>
  603. </div>
  604. )
  605. }
  606. export default React.memo(Main)