index.tsx 29 KB

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