index.tsx 25 KB

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