index.tsx 29 KB

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