index.tsx 24 KB

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