index.tsx 25 KB

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