index.tsx 26 KB

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