index.tsx 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724
  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. icon: installedAppInfo?.app.icon,
  316. icon_background: installedAppInfo?.app.icon_background,
  317. prompt_public: false,
  318. copyright: '',
  319. },
  320. plan: 'basic',
  321. }
  322. : fetchAppInfo(), fetchAllConversations(), fetchAppParams(isInstalledApp, installedAppInfo?.id)])
  323. }
  324. // init
  325. useEffect(() => {
  326. (async () => {
  327. try {
  328. const [appData, conversationData, appParams]: any = await fetchInitData()
  329. const { app_id: appId, site: siteInfo, plan }: any = appData
  330. setAppId(appId)
  331. setPlan(plan)
  332. const tempIsPublicVersion = siteInfo.prompt_public
  333. setIsPublicVersion(tempIsPublicVersion)
  334. const prompt_template = ''
  335. // handle current conversation id
  336. const { data: allConversations } = conversationData as { data: ConversationItem[]; has_more: boolean }
  337. const _conversationId = getConversationIdFromStorage(appId)
  338. const isNotNewConversation = allConversations.some(item => item.id === _conversationId)
  339. setAllConversationList(allConversations)
  340. // fetch new conversation info
  341. const { user_input_form, opening_statement: introduction, suggested_questions_after_answer, speech_to_text, retriever_resource }: any = appParams
  342. const prompt_variables = userInputsFormToPromptVariables(user_input_form)
  343. if (siteInfo.default_language)
  344. changeLanguage(siteInfo.default_language)
  345. setNewConversationInfo({
  346. name: t('share.chat.newChatDefaultName'),
  347. introduction,
  348. })
  349. setSiteInfo(siteInfo as SiteInfo)
  350. setPromptConfig({
  351. prompt_template,
  352. prompt_variables,
  353. } as PromptConfig)
  354. setSuggestedQuestionsAfterAnswerConfig(suggested_questions_after_answer)
  355. setSpeechToTextConfig(speech_to_text)
  356. setCitationConfig(retriever_resource)
  357. // setConversationList(conversations as ConversationItem[])
  358. if (isNotNewConversation)
  359. setCurrConversationId(_conversationId, appId, false)
  360. setInited(true)
  361. }
  362. catch (e: any) {
  363. if (e.status === 404) {
  364. setAppUnavailable(true)
  365. }
  366. else {
  367. setIsUnknwonReason(true)
  368. setAppUnavailable(true)
  369. }
  370. }
  371. })()
  372. }, [])
  373. const [isResponsing, { setTrue: setResponsingTrue, setFalse: setResponsingFalse }] = useBoolean(false)
  374. const [abortController, setAbortController] = useState<AbortController | null>(null)
  375. const { notify } = useContext(ToastContext)
  376. const logError = (message: string) => {
  377. notify({ type: 'error', message })
  378. }
  379. const checkCanSend = () => {
  380. if (currConversationId !== '-1')
  381. return true
  382. const prompt_variables = promptConfig?.prompt_variables
  383. const inputs = currInputs
  384. if (!inputs || !prompt_variables || prompt_variables?.length === 0)
  385. return true
  386. let hasEmptyInput = ''
  387. const requiredVars = prompt_variables?.filter(({ key, name, required }) => {
  388. const res = (!key || !key.trim()) || (!name || !name.trim()) || (required || required === undefined || required === null)
  389. return res
  390. }) || [] // compatible with old version
  391. requiredVars.forEach(({ key, name }) => {
  392. if (hasEmptyInput)
  393. return
  394. if (!inputs?.[key])
  395. hasEmptyInput = name
  396. })
  397. if (hasEmptyInput) {
  398. logError(t('appDebug.errorMessage.valueOfVarRequired', { key: hasEmptyInput }))
  399. return false
  400. }
  401. return !hasEmptyInput
  402. }
  403. const [controlFocus, setControlFocus] = useState(0)
  404. const [isShowSuggestion, setIsShowSuggestion] = useState(false)
  405. const doShowSuggestion = isShowSuggestion && !isResponsing
  406. const [suggestQuestions, setSuggestQuestions] = useState<string[]>([])
  407. const [messageTaskId, setMessageTaskId] = useState('')
  408. const [hasStopResponded, setHasStopResponded, getHasStopResponded] = useGetState(false)
  409. const [isResponsingConIsCurrCon, setIsResponsingConCurrCon, getIsResponsingConIsCurrCon] = useGetState(true)
  410. const handleSend = async (message: string) => {
  411. if (isResponsing) {
  412. notify({ type: 'info', message: t('appDebug.errorMessage.waitForResponse') })
  413. return
  414. }
  415. const data = {
  416. inputs: currInputs,
  417. query: message,
  418. conversation_id: isNewConversation ? null : currConversationId,
  419. }
  420. // qustion
  421. const questionId = `question-${Date.now()}`
  422. const questionItem = {
  423. id: questionId,
  424. content: message,
  425. isAnswer: false,
  426. }
  427. const placeholderAnswerId = `answer-placeholder-${Date.now()}`
  428. const placeholderAnswerItem = {
  429. id: placeholderAnswerId,
  430. content: '',
  431. isAnswer: true,
  432. }
  433. const newList = [...getChatList(), questionItem, placeholderAnswerItem]
  434. setChatList(newList)
  435. // answer
  436. const responseItem: IChatItem = {
  437. id: `${Date.now()}`,
  438. content: '',
  439. isAnswer: true,
  440. }
  441. const prevTempNewConversationId = getCurrConversationId() || '-1'
  442. let tempNewConversationId = prevTempNewConversationId
  443. setHasStopResponded(false)
  444. setResponsingTrue()
  445. setIsShowSuggestion(false)
  446. setIsResponsingConCurrCon(true)
  447. sendChatMessage(data, {
  448. getAbortController: (abortController) => {
  449. setAbortController(abortController)
  450. },
  451. onData: (message: string, isFirstMessage: boolean, { conversationId: newConversationId, messageId, taskId }: any) => {
  452. responseItem.content = responseItem.content + message
  453. responseItem.id = messageId
  454. if (isFirstMessage && newConversationId)
  455. tempNewConversationId = newConversationId
  456. setMessageTaskId(taskId)
  457. // has switched to other conversation
  458. if (prevTempNewConversationId !== getCurrConversationId()) {
  459. setIsResponsingConCurrCon(false)
  460. return
  461. }
  462. // closesure new list is outdated.
  463. const newListWithAnswer = produce(
  464. getChatList().filter(item => item.id !== responseItem.id && item.id !== placeholderAnswerId),
  465. (draft) => {
  466. if (!draft.find(item => item.id === questionId))
  467. draft.push({ ...questionItem })
  468. draft.push({ ...responseItem })
  469. })
  470. setChatList(newListWithAnswer)
  471. },
  472. async onCompleted(hasError?: boolean) {
  473. setResponsingFalse()
  474. if (hasError)
  475. return
  476. if (getConversationIdChangeBecauseOfNew()) {
  477. const { data: allConversations }: any = await fetchAllConversations()
  478. setAllConversationList(allConversations)
  479. noticeUpdateList()
  480. }
  481. setConversationIdChangeBecauseOfNew(false)
  482. resetNewConversationInputs()
  483. setChatNotStarted()
  484. setCurrConversationId(tempNewConversationId, appId, true)
  485. if (getIsResponsingConIsCurrCon() && suggestedQuestionsAfterAnswerConfig?.enabled && !getHasStopResponded()) {
  486. const { data }: any = await fetchSuggestedQuestions(responseItem.id, isInstalledApp, installedAppInfo?.id)
  487. setSuggestQuestions(data)
  488. setIsShowSuggestion(true)
  489. }
  490. },
  491. onMessageEnd: isInstalledApp
  492. ? (messageEnd) => {
  493. if (!isInstalledApp)
  494. return
  495. responseItem.citation = messageEnd.retriever_resources
  496. const newListWithAnswer = produce(
  497. getChatList().filter(item => item.id !== responseItem.id && item.id !== placeholderAnswerId),
  498. (draft) => {
  499. if (!draft.find(item => item.id === questionId))
  500. draft.push({ ...questionItem })
  501. draft.push({ ...responseItem })
  502. })
  503. setChatList(newListWithAnswer)
  504. }
  505. : undefined,
  506. onError() {
  507. setResponsingFalse()
  508. // role back placeholder answer
  509. setChatList(produce(getChatList(), (draft) => {
  510. draft.splice(draft.findIndex(item => item.id === placeholderAnswerId), 1)
  511. }))
  512. },
  513. }, isInstalledApp, installedAppInfo?.id)
  514. }
  515. const handleFeedback = async (messageId: string, feedback: Feedbacktype) => {
  516. await updateFeedback({ url: `/messages/${messageId}/feedbacks`, body: { rating: feedback.rating } }, isInstalledApp, installedAppInfo?.id)
  517. const newChatList = chatList.map((item) => {
  518. if (item.id === messageId) {
  519. return {
  520. ...item,
  521. feedback,
  522. }
  523. }
  524. return item
  525. })
  526. setChatList(newChatList)
  527. notify({ type: 'success', message: t('common.api.success') })
  528. }
  529. const renderSidebar = () => {
  530. if (!appId || !siteInfo || !promptConfig)
  531. return null
  532. return (
  533. <Sidebar
  534. list={conversationList}
  535. onListChanged={(list) => {
  536. setConversationList(list)
  537. setControlChatUpdateAllConversation(Date.now())
  538. }}
  539. isClearConversationList={isClearConversationList}
  540. pinnedList={pinnedConversationList}
  541. onPinnedListChanged={(list) => {
  542. setPinnedConversationList(list)
  543. setControlChatUpdateAllConversation(Date.now())
  544. }}
  545. isClearPinnedConversationList={isClearPinnedConversationList}
  546. onMoreLoaded={onMoreLoaded}
  547. onPinnedMoreLoaded={onPinnedMoreLoaded}
  548. isNoMore={!hasMore}
  549. isPinnedNoMore={!hasPinnedMore}
  550. onCurrentIdChange={handleConversationIdChange}
  551. currentId={currConversationId}
  552. copyRight={siteInfo.copyright || siteInfo.title}
  553. isInstalledApp={isInstalledApp}
  554. installedAppId={installedAppInfo?.id}
  555. siteInfo={siteInfo}
  556. onPin={handlePin}
  557. onUnpin={handleUnpin}
  558. controlUpdateList={controlUpdateConversationList}
  559. onDelete={handleDelete}
  560. />
  561. )
  562. }
  563. if (appUnavailable)
  564. return <AppUnavailable isUnknwonReason={isUnknwonReason} />
  565. if (!appId || !siteInfo || !promptConfig) {
  566. return <div className='flex h-screen w-full'>
  567. <Loading type='app' />
  568. </div>
  569. }
  570. return (
  571. <div className='bg-gray-100'>
  572. {!isInstalledApp && (
  573. <Header
  574. title={siteInfo.title}
  575. icon={siteInfo.icon || ''}
  576. icon_background={siteInfo.icon_background}
  577. isMobile={isMobile}
  578. onShowSideBar={showSidebar}
  579. onCreateNewChat={() => handleConversationIdChange('-1')}
  580. />
  581. )}
  582. <div
  583. className={cn(
  584. 'flex rounded-t-2xl bg-white overflow-hidden h-full w-full',
  585. isInstalledApp && 'rounded-b-2xl',
  586. )}
  587. style={isInstalledApp
  588. ? {
  589. boxShadow: '0px 12px 16px -4px rgba(16, 24, 40, 0.08), 0px 4px 6px -2px rgba(16, 24, 40, 0.03)',
  590. }
  591. : {}}
  592. >
  593. {/* sidebar */}
  594. {!isMobile && renderSidebar()}
  595. {isMobile && isShowSidebar && (
  596. <div className='fixed inset-0 z-50'
  597. style={{ backgroundColor: 'rgba(35, 56, 118, 0.2)' }}
  598. onClick={hideSidebar}
  599. >
  600. <div className='inline-block' onClick={e => e.stopPropagation()}>
  601. {renderSidebar()}
  602. </div>
  603. </div>
  604. )}
  605. {/* main */}
  606. <div className={cn(
  607. isInstalledApp ? s.installedApp : 'h-[calc(100vh_-_3rem)] tablet:h-screen',
  608. 'flex-grow flex flex-col overflow-y-auto',
  609. )
  610. }>
  611. <ConfigSence
  612. conversationName={conversationName}
  613. hasSetInputs={hasSetInputs}
  614. isPublicVersion={isPublicVersion}
  615. siteInfo={siteInfo}
  616. promptConfig={promptConfig}
  617. onStartChat={handleStartChat}
  618. canEidtInpus={canEditInpus}
  619. savedInputs={currInputs as Record<string, any>}
  620. onInputsChange={setCurrInputs}
  621. plan={plan}
  622. ></ConfigSence>
  623. {
  624. hasSetInputs && (
  625. <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')}>
  626. <div className='h-full overflow-y-auto' ref={chatListDomRef}>
  627. <Chat
  628. chatList={chatList}
  629. onSend={handleSend}
  630. isHideFeedbackEdit
  631. onFeedback={handleFeedback}
  632. isResponsing={isResponsing}
  633. canStopResponsing={!!messageTaskId && isResponsingConIsCurrCon}
  634. abortResponsing={async () => {
  635. await stopChatMessageResponding(appId, messageTaskId, isInstalledApp, installedAppInfo?.id)
  636. setHasStopResponded(true)
  637. setResponsingFalse()
  638. }}
  639. checkCanSend={checkCanSend}
  640. controlFocus={controlFocus}
  641. isShowSuggestion={doShowSuggestion}
  642. suggestionList={suggestQuestions}
  643. isShowSpeechToText={speechToTextConfig?.enabled}
  644. isShowCitation={citationConfig?.enabled && isInstalledApp}
  645. />
  646. </div>
  647. </div>)
  648. }
  649. {isShowConfirm && (
  650. <Confirm
  651. title={t('share.chat.deleteConversation.title')}
  652. content={t('share.chat.deleteConversation.content')}
  653. isShow={isShowConfirm}
  654. onClose={hideConfirm}
  655. onConfirm={didDelete}
  656. onCancel={hideConfirm}
  657. />
  658. )}
  659. </div>
  660. </div>
  661. </div>
  662. )
  663. }
  664. export default React.memo(Main)