index.tsx 23 KB

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