index.tsx 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  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 [visionConfig, setVisionConfig] = useState<VisionSettings>({
  349. enabled: false,
  350. number_limits: 2,
  351. detail: Resolution.low,
  352. transfer_methods: [TransferMethod.local_file],
  353. })
  354. const handleSend = async (message: string, files?: VisionFile[]) => {
  355. if (isResponsing) {
  356. notify({ type: 'info', message: t('appDebug.errorMessage.waitForResponse') })
  357. return
  358. }
  359. if (files?.find(item => item.transfer_method === TransferMethod.local_file && !item.upload_file_id)) {
  360. notify({ type: 'info', message: t('appDebug.errorMessage.waitForImgUpload') })
  361. return false
  362. }
  363. const data: Record<string, any> = {
  364. inputs: currInputs,
  365. query: message,
  366. conversation_id: isNewConversation ? null : currConversationId,
  367. }
  368. if (visionConfig.enabled && files && files?.length > 0) {
  369. data.files = files.map((item) => {
  370. if (item.transfer_method === TransferMethod.local_file) {
  371. return {
  372. ...item,
  373. url: '',
  374. }
  375. }
  376. return item
  377. })
  378. }
  379. // qustion
  380. const questionId = `question-${Date.now()}`
  381. const questionItem = {
  382. id: questionId,
  383. content: message,
  384. isAnswer: false,
  385. message_files: files,
  386. }
  387. const placeholderAnswerId = `answer-placeholder-${Date.now()}`
  388. const placeholderAnswerItem = {
  389. id: placeholderAnswerId,
  390. content: '',
  391. isAnswer: true,
  392. }
  393. const newList = [...getChatList(), questionItem, placeholderAnswerItem]
  394. setChatList(newList)
  395. // answer
  396. const responseItem: IChatItem = {
  397. id: `${Date.now()}`,
  398. content: '',
  399. isAnswer: true,
  400. }
  401. let tempNewConversationId = ''
  402. setHasStopResponded(false)
  403. setResponsingTrue()
  404. setIsShowSuggestion(false)
  405. sendChatMessage(data, {
  406. getAbortController: (abortController) => {
  407. setAbortController(abortController)
  408. },
  409. onData: (message: string, isFirstMessage: boolean, { conversationId: newConversationId, messageId, taskId }: any) => {
  410. responseItem.content = responseItem.content + message
  411. responseItem.id = messageId
  412. if (isFirstMessage && newConversationId)
  413. tempNewConversationId = newConversationId
  414. setMessageTaskId(taskId)
  415. // closesure new list is outdated.
  416. const newListWithAnswer = produce(
  417. getChatList().filter(item => item.id !== responseItem.id && item.id !== placeholderAnswerId),
  418. (draft) => {
  419. if (!draft.find(item => item.id === questionId))
  420. draft.push({ ...questionItem })
  421. draft.push({ ...responseItem })
  422. })
  423. setChatList(newListWithAnswer)
  424. },
  425. async onCompleted(hasError?: boolean) {
  426. if (hasError)
  427. return
  428. if (getConversationIdChangeBecauseOfNew()) {
  429. const { data: allConversations }: any = await fetchAllConversations()
  430. const newItem: any = await generationConversationName(isInstalledApp, installedAppInfo?.id, allConversations[0].id)
  431. const newAllConversations = produce(allConversations, (draft: any) => {
  432. draft[0].name = newItem.name
  433. })
  434. setAllConversationList(newAllConversations as any)
  435. noticeUpdateList()
  436. }
  437. setConversationIdChangeBecauseOfNew(false)
  438. resetNewConversationInputs()
  439. setChatNotStarted()
  440. setCurrConversationId(tempNewConversationId, appId, true)
  441. if (suggestedQuestionsAfterAnswerConfig?.enabled && !getHasStopResponded()) {
  442. const { data }: any = await fetchSuggestedQuestions(responseItem.id, isInstalledApp, installedAppInfo?.id)
  443. setSuggestQuestions(data)
  444. setIsShowSuggestion(true)
  445. }
  446. setResponsingFalse()
  447. },
  448. onMessageReplace: (messageReplace) => {
  449. setChatList(produce(
  450. getChatList(),
  451. (draft) => {
  452. const current = draft.find(item => item.id === messageReplace.id)
  453. if (current)
  454. current.content = messageReplace.answer
  455. },
  456. ))
  457. },
  458. onError(errorMessage, errorCode) {
  459. if (['provider_not_initialize', 'completion_request_error'].includes(errorCode as string))
  460. setShouldReload(true)
  461. setResponsingFalse()
  462. // role back placeholder answer
  463. setChatList(produce(getChatList(), (draft) => {
  464. draft.splice(draft.findIndex(item => item.id === placeholderAnswerId), 1)
  465. }))
  466. },
  467. }, isInstalledApp, installedAppInfo?.id)
  468. }
  469. const handleFeedback = async (messageId: string, feedback: Feedbacktype) => {
  470. await updateFeedback({ url: `/messages/${messageId}/feedbacks`, body: { rating: feedback.rating } }, isInstalledApp, installedAppInfo?.id)
  471. const newChatList = chatList.map((item) => {
  472. if (item.id === messageId) {
  473. return {
  474. ...item,
  475. feedback,
  476. }
  477. }
  478. return item
  479. })
  480. setChatList(newChatList)
  481. notify({ type: 'success', message: t('common.api.success') })
  482. }
  483. const handleReload = () => {
  484. setCurrConversationId('-1', appId, false)
  485. setChatNotStarted()
  486. setShouldReload(false)
  487. createNewChat()
  488. }
  489. const handleConversationIdChange = (id: string) => {
  490. if (id === '-1') {
  491. createNewChat()
  492. setConversationIdChangeBecauseOfNew(true)
  493. }
  494. else {
  495. setConversationIdChangeBecauseOfNew(false)
  496. }
  497. // trigger handleConversationSwitch
  498. setCurrConversationId(id, appId)
  499. setIsShowSuggestion(false)
  500. }
  501. const difyIcon = (
  502. <LogoHeader />
  503. )
  504. if (appUnavailable)
  505. return <AppUnavailable isUnknwonReason={isUnknwonReason} />
  506. if (!appId || !siteInfo || !promptConfig) {
  507. return <div className='flex h-screen w-full'>
  508. <Loading type='app' />
  509. </div>
  510. }
  511. return (
  512. <div>
  513. <Header
  514. title={siteInfo.title}
  515. icon=''
  516. customerIcon={difyIcon}
  517. icon_background={siteInfo.icon_background}
  518. isEmbedScene={true}
  519. isMobile={isMobile}
  520. onCreateNewChat={() => handleConversationIdChange('-1')}
  521. />
  522. <div className={'flex bg-white overflow-hidden'}>
  523. <div className={cn(
  524. isInstalledApp ? 'h-full' : 'h-[calc(100vh_-_3rem)]',
  525. 'flex-grow flex flex-col overflow-y-auto',
  526. )
  527. }>
  528. <ConfigScene
  529. // conversationName={conversationName}
  530. hasSetInputs={hasSetInputs}
  531. isPublicVersion={isPublicVersion}
  532. siteInfo={siteInfo}
  533. promptConfig={promptConfig}
  534. onStartChat={handleStartChat}
  535. canEditInputs={canEditInputs}
  536. savedInputs={currInputs as Record<string, any>}
  537. onInputsChange={setCurrInputs}
  538. plan={plan}
  539. canReplaceLogo={canReplaceLogo}
  540. customConfig={customConfig}
  541. ></ConfigScene>
  542. {
  543. shouldReload && (
  544. <div className='flex items-center justify-between mb-5 px-4 py-2 bg-[#FEF0C7]'>
  545. <div className='flex items-center text-xs font-medium text-[#DC6803]'>
  546. <AlertTriangle className='mr-2 w-4 h-4' />
  547. {t('share.chat.temporarySystemIssue')}
  548. </div>
  549. <div
  550. className='flex items-center px-3 h-7 bg-white shadow-xs rounded-md text-xs font-medium text-gray-700 cursor-pointer'
  551. onClick={handleReload}
  552. >
  553. {t('share.chat.tryToSolve')}
  554. </div>
  555. </div>
  556. )
  557. }
  558. {
  559. hasSetInputs && (
  560. <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')}>
  561. <div className='h-full overflow-y-auto' ref={chatListDomRef}>
  562. <Chat
  563. chatList={chatList}
  564. onSend={handleSend}
  565. isHideFeedbackEdit
  566. onFeedback={handleFeedback}
  567. isResponsing={isResponsing}
  568. canStopResponsing={!!messageTaskId}
  569. abortResponsing={async () => {
  570. await stopChatMessageResponding(appId, messageTaskId, isInstalledApp, installedAppInfo?.id)
  571. setHasStopResponded(true)
  572. setResponsingFalse()
  573. }}
  574. checkCanSend={checkCanSend}
  575. controlFocus={controlFocus}
  576. isShowSuggestion={doShowSuggestion}
  577. suggestionList={suggestQuestions}
  578. displayScene='web'
  579. isShowSpeechToText={speechToTextConfig?.enabled}
  580. isShowTextToSpeech={textToSpeechConfig?.enabled}
  581. isShowCitation={citationConfig?.enabled && isInstalledApp}
  582. answerIcon={<LogoAvatar className='relative shrink-0' />}
  583. visionConfig={visionConfig}
  584. />
  585. </div>
  586. </div>)
  587. }
  588. {/* {isShowConfirm && (
  589. <Confirm
  590. title={t('share.chat.deleteConversation.title')}
  591. content={t('share.chat.deleteConversation.content')}
  592. isShow={isShowConfirm}
  593. onClose={hideConfirm}
  594. onConfirm={didDelete}
  595. onCancel={hideConfirm}
  596. />
  597. )} */}
  598. </div>
  599. </div>
  600. </div>
  601. )
  602. }
  603. export default React.memo(Main)