index.tsx 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823
  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. import { useProviderContext } from '@/context/provider-context'
  43. import type { ProviderEnum } from '@/app/components/header/account-setting/model-page/declarations'
  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]?.model_provider.provider_name,
  77. modelId: prevConfig?.modelId || agentThoughtModelList?.[0]?.model_name,
  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 handleSend = async (message: string) => {
  416. if (isNewConversation) {
  417. const isModelSelected = modelId && !!agentThoughtModelList.find(item => item.model_name === modelId)
  418. if (!isModelSelected) {
  419. notify({ type: 'error', message: t('appDebug.errorMessage.notSelectModel') })
  420. return
  421. }
  422. setPrevConfig({
  423. modelId,
  424. providerName,
  425. plugin: plugins as any,
  426. })
  427. }
  428. if (isResponsing) {
  429. notify({ type: 'info', message: t('appDebug.errorMessage.waitForResponse') })
  430. return
  431. }
  432. const formattedPlugins = Object.keys(plugins).map(key => ({
  433. [key]: {
  434. enabled: plugins[key],
  435. },
  436. }))
  437. const formattedDataSets = dataSets.map(({ id }) => {
  438. return {
  439. dataset: {
  440. enabled: true,
  441. id,
  442. },
  443. }
  444. })
  445. const data = {
  446. query: message,
  447. conversation_id: isNewConversation ? null : currConversationId,
  448. model: modelId,
  449. provider: providerName,
  450. tools: [...formattedPlugins, ...formattedDataSets],
  451. }
  452. // qustion
  453. const questionId = `question-${Date.now()}`
  454. const questionItem = {
  455. id: questionId,
  456. content: message,
  457. agent_thoughts: [],
  458. isAnswer: false,
  459. }
  460. const placeholderAnswerId = `answer-placeholder-${Date.now()}`
  461. const placeholderAnswerItem = {
  462. id: placeholderAnswerId,
  463. content: '',
  464. isAnswer: true,
  465. }
  466. const newList = [...getChatList(), questionItem, placeholderAnswerItem]
  467. setChatList(newList)
  468. // answer
  469. const responseItem: IChatItem = {
  470. id: `${Date.now()}`,
  471. content: '',
  472. agent_thoughts: [],
  473. isAnswer: true,
  474. }
  475. const prevTempNewConversationId = getCurrConversationId() || '-1'
  476. let tempNewConversationId = prevTempNewConversationId
  477. setHasStopResponded(false)
  478. setResponsingTrue()
  479. setErrorHappened(false)
  480. setIsShowSuggestion(false)
  481. setIsResponsingConCurrCon(true)
  482. sendChatMessage(data, {
  483. getAbortController: (abortController) => {
  484. setAbortController(abortController)
  485. },
  486. onData: (message: string, isFirstMessage: boolean, { conversationId: newConversationId, messageId, taskId }: any) => {
  487. responseItem.content = responseItem.content + message
  488. responseItem.id = messageId
  489. if (isFirstMessage && newConversationId)
  490. tempNewConversationId = newConversationId
  491. setMessageTaskId(taskId)
  492. // has switched to other conversation
  493. if (prevTempNewConversationId !== getCurrConversationId()) {
  494. setIsResponsingConCurrCon(false)
  495. return
  496. }
  497. // closesure new list is outdated.
  498. const newListWithAnswer = produce(
  499. getChatList().filter(item => item.id !== responseItem.id && item.id !== placeholderAnswerId),
  500. (draft) => {
  501. if (!draft.find(item => item.id === questionId))
  502. draft.push({ ...questionItem } as any)
  503. draft.push({ ...responseItem })
  504. })
  505. setChatList(newListWithAnswer)
  506. },
  507. async onCompleted(hasError?: boolean) {
  508. if (hasError) {
  509. setResponsingFalse()
  510. return
  511. }
  512. if (getConversationIdChangeBecauseOfNew()) {
  513. const { data: allConversations }: any = await fetchAllConversations()
  514. setAllConversationList(allConversations)
  515. noticeUpdateList()
  516. }
  517. setConversationIdChangeBecauseOfNew(false)
  518. resetNewConversationInputs()
  519. setCurrConversationId(tempNewConversationId, APP_ID, true)
  520. if (getIsResponsingConIsCurrCon() && suggestedQuestionsAfterAnswerConfig?.enabled && !getHasStopResponded()) {
  521. const { data }: any = await fetchSuggestedQuestions(responseItem.id)
  522. setSuggestQuestions(data)
  523. setIsShowSuggestion(true)
  524. }
  525. setResponsingFalse()
  526. },
  527. onThought(thought) {
  528. // thought finished then start to return message. Warning: use push agent_thoughts.push would caused problem when the thought is more then 2
  529. responseItem.id = thought.message_id;
  530. (responseItem as any).agent_thoughts = [...(responseItem as any).agent_thoughts, thought] // .push(thought)
  531. // has switched to other conversation
  532. if (prevTempNewConversationId !== getCurrConversationId()) {
  533. setIsResponsingConCurrCon(false)
  534. return
  535. }
  536. const newListWithAnswer = produce(
  537. getChatList().filter(item => item.id !== responseItem.id && item.id !== placeholderAnswerId),
  538. (draft) => {
  539. if (!draft.find(item => item.id === questionId))
  540. draft.push({ ...questionItem })
  541. draft.push({ ...responseItem })
  542. })
  543. setChatList(newListWithAnswer)
  544. },
  545. onMessageEnd: (messageEnd) => {
  546. responseItem.citation = messageEnd.retriever_resources
  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. onError() {
  557. setErrorHappened(true)
  558. // role back placeholder answer
  559. setChatList(produce(getChatList(), (draft) => {
  560. draft.splice(draft.findIndex(item => item.id === placeholderAnswerId), 1)
  561. }))
  562. setResponsingFalse()
  563. },
  564. })
  565. }
  566. const handleFeedback = async (messageId: string, feedback: Feedbacktype) => {
  567. await updateFeedback({ url: `/messages/${messageId}/feedbacks`, body: { rating: feedback.rating } })
  568. const newChatList = chatList.map((item) => {
  569. if (item.id === messageId) {
  570. return {
  571. ...item,
  572. feedback,
  573. }
  574. }
  575. return item
  576. })
  577. setChatList(newChatList)
  578. notify({ type: 'success', message: t('common.api.success') })
  579. }
  580. const [controlChatUpdateAllConversation, setControlChatUpdateAllConversation] = useState(0)
  581. useEffect(() => {
  582. (async () => {
  583. if (controlChatUpdateAllConversation && !isNewConversation) {
  584. const { data: allConversations } = await fetchAllConversations() as { data: ConversationItem[]; has_more: boolean }
  585. const item = allConversations.find(item => item.id === currConversationId)
  586. setAllConversationList(allConversations)
  587. if (item) {
  588. setExistConversationInfo({
  589. ...existConversationInfo,
  590. name: item?.name || '',
  591. } as any)
  592. }
  593. }
  594. })()
  595. }, [controlChatUpdateAllConversation])
  596. const renderSidebar = () => {
  597. if (!APP_ID || !promptConfig)
  598. return null
  599. return (
  600. <Sidebar
  601. list={conversationList}
  602. onListChanged={(list) => {
  603. setConversationList(list)
  604. setControlChatUpdateAllConversation(Date.now())
  605. }}
  606. isClearConversationList={isClearConversationList}
  607. pinnedList={pinnedConversationList}
  608. onPinnedListChanged={(list) => {
  609. setPinnedConversationList(list)
  610. setControlChatUpdateAllConversation(Date.now())
  611. }}
  612. isClearPinnedConversationList={isClearPinnedConversationList}
  613. onMoreLoaded={onMoreLoaded}
  614. onPinnedMoreLoaded={onPinnedMoreLoaded}
  615. isNoMore={!hasMore}
  616. isPinnedNoMore={!hasPinnedMore}
  617. onCurrentIdChange={handleConversationIdChange}
  618. currentId={currConversationId}
  619. copyRight={''}
  620. isInstalledApp={false}
  621. isUniversalChat
  622. installedAppId={''}
  623. siteInfo={siteInfo}
  624. onPin={handlePin}
  625. onUnpin={handleUnpin}
  626. controlUpdateList={controlUpdateConversationList}
  627. onDelete={handleDelete}
  628. />
  629. )
  630. }
  631. const initConfig = getInitConfig('model')
  632. const [modelId, setModeId] = useState<string>((initConfig as any)?.modelId as string)
  633. const [providerName, setProviderName] = useState<ProviderEnum>((initConfig as any)?.providerName as ProviderEnum)
  634. // const currModel = MODEL_LIST.find(item => item.id === modelId)
  635. const [plugins, setPlugins] = useState<Record<string, boolean>>(getInitConfig('plugin') as Record<string, boolean>)
  636. const handlePluginsChange = (key: string, value: boolean) => {
  637. setPlugins({
  638. ...plugins,
  639. [key]: value,
  640. })
  641. }
  642. const [dataSets, setDateSets] = useState<DataSet[]>([])
  643. const configSetDefaultValue = () => {
  644. const initConfig = getInitConfig('model')
  645. setModeId((initConfig as any)?.modelId as string)
  646. setProviderName((initConfig as any)?.providerName as ProviderEnum)
  647. setPlugins(getInitConfig('plugin') as any)
  648. setDateSets([])
  649. }
  650. const isCurrConversationPinned = !!pinnedConversationList.find(item => item.id === currConversationId)
  651. const [controlItemOpHide, setControlItemOpHide] = useState(0)
  652. if (appUnavailable)
  653. return <AppUnavailable isUnknwonReason={isUnknwonReason} />
  654. if (!promptConfig)
  655. return <Loading type='app' />
  656. return (
  657. <div className='bg-gray-100'>
  658. <div
  659. className={cn(
  660. 'flex rounded-t-2xl bg-white overflow-hidden rounded-b-2xl',
  661. )}
  662. style={{
  663. boxShadow: '0px 12px 16px -4px rgba(16, 24, 40, 0.08), 0px 4px 6px -2px rgba(16, 24, 40, 0.03)',
  664. }}
  665. >
  666. {/* sidebar */}
  667. {!isMobile && renderSidebar()}
  668. {isMobile && isShowSidebar && (
  669. <div className='fixed inset-0 z-50'
  670. style={{ backgroundColor: 'rgba(35, 56, 118, 0.2)' }}
  671. onClick={hideSidebar}
  672. >
  673. <div className='inline-block' onClick={e => e.stopPropagation()}>
  674. {renderSidebar()}
  675. </div>
  676. </div>
  677. )}
  678. {/* main */}
  679. <div className={cn(
  680. s.installedApp,
  681. 'flex-grow flex flex-col overflow-y-auto',
  682. )
  683. }>
  684. {(!isNewConversation || isResponsing || errorHappened) && (
  685. <div className='mb-5 antialiased font-sans shrink-0 relative mobile:min-h-[48px] tablet:min-h-[64px]'>
  686. <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'>
  687. <div className='text-gray-900'>{conversationName}</div>
  688. <div className='flex items-center shrink-0 ml-2 space-x-2'>
  689. <ConfigSummary
  690. modelId={modelId}
  691. providerName={providerName}
  692. plugins={plugins}
  693. dataSets={dataSets}
  694. />
  695. <div className={cn('flex w-8 h-8 justify-center items-center shrink-0 rounded-lg border border-gray-200')} onClick={e => e.stopPropagation()}>
  696. <ItemOperation
  697. key={controlItemOpHide}
  698. className='!w-8 !h-8'
  699. isPinned={isCurrConversationPinned}
  700. togglePin={() => isCurrConversationPinned ? handleUnpin(currConversationId) : handlePin(currConversationId)}
  701. isShowDelete
  702. onDelete={() => handleDelete(currConversationId)}
  703. />
  704. </div>
  705. </div>
  706. </div>
  707. </div>
  708. )}
  709. <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')}>
  710. <div className={cn('pc:w-[794px] max-w-full mobile:w-full mx-auto h-full overflow-y-auto')} ref={chatListDomRef}>
  711. <Chat
  712. isShowConfigElem={isNewConversation && chatList.length === 0}
  713. configElem={<Init
  714. modelId={modelId}
  715. providerName={providerName}
  716. onModelChange={(modelId, providerName) => {
  717. setModeId(modelId)
  718. setProviderName(providerName)
  719. }}
  720. plugins={plugins}
  721. onPluginChange={handlePluginsChange}
  722. dataSets={dataSets}
  723. onDataSetsChange={setDateSets}
  724. />}
  725. chatList={chatList}
  726. onSend={handleSend}
  727. isHideFeedbackEdit
  728. onFeedback={handleFeedback}
  729. isResponsing={isResponsing}
  730. canStopResponsing={!!messageTaskId && isResponsingConIsCurrCon}
  731. abortResponsing={async () => {
  732. await stopChatMessageResponding(messageTaskId)
  733. setHasStopResponded(true)
  734. setResponsingFalse()
  735. }}
  736. checkCanSend={checkCanSend}
  737. controlFocus={controlFocus}
  738. isShowSuggestion={doShowSuggestion}
  739. suggestionList={suggestQuestions}
  740. isShowSpeechToText={speechToTextConfig?.enabled}
  741. isShowCitation={citationConfig?.enabled}
  742. dataSets={dataSets}
  743. />
  744. </div>
  745. </div>
  746. {isShowConfirm && (
  747. <Confirm
  748. title={t('share.chat.deleteConversation.title')}
  749. content={t('share.chat.deleteConversation.content')}
  750. isShow={isShowConfirm}
  751. onClose={hideConfirm}
  752. onConfirm={didDelete}
  753. onCancel={hideConfirm}
  754. />
  755. )}
  756. </div>
  757. </div>
  758. </div>
  759. )
  760. }
  761. export default React.memo(Main)