index.tsx 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807
  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 [conversationIdChangeBecauseOfNew, setConversationIdChangeBecauseOfNew, getConversationIdChangeBecauseOfNew] = useGetState(false)
  192. const conversationName = currConversationInfo?.name || t('share.chat.newChatDefaultName') as string
  193. const conversationIntroduction = currConversationInfo?.introduction || ''
  194. const handleConversationSwitch = async () => {
  195. if (!inited)
  196. return
  197. // update inputs of current conversation
  198. let notSyncToStateIntroduction = ''
  199. let notSyncToStateInputs: Record<string, any> | undefined | null = {}
  200. // debugger
  201. if (!isNewConversation) {
  202. const item = allConversationList.find(item => item.id === currConversationId) as any
  203. notSyncToStateInputs = item?.inputs || {}
  204. // setCurrInputs(notSyncToStateInputs)
  205. notSyncToStateIntroduction = item?.introduction || ''
  206. setExistConversationInfo({
  207. name: item?.name || '',
  208. introduction: notSyncToStateIntroduction,
  209. })
  210. const modelConfig = item?.model_config
  211. if (modelConfig) {
  212. setModeId(modelConfig.model_id)
  213. const pluginConfig: Record<string, boolean> = {}
  214. const datasetIds: string[] = []
  215. modelConfig.agent_mode.tools.forEach((item: any) => {
  216. const pluginName = Object.keys(item)[0]
  217. if (pluginName === 'dataset')
  218. datasetIds.push(item.dataset.id)
  219. else
  220. pluginConfig[pluginName] = item[pluginName].enabled
  221. })
  222. setPlugins(pluginConfig)
  223. if (datasetIds.length > 0) {
  224. const { data } = await fetchDatasets({ url: '/datasets', params: { page: 1, ids: datasetIds } })
  225. setDateSets(data)
  226. }
  227. else {
  228. setDateSets([])
  229. }
  230. }
  231. else {
  232. configSetDefaultValue()
  233. }
  234. }
  235. else {
  236. configSetDefaultValue()
  237. notSyncToStateInputs = newConversationInputs
  238. setCurrInputs(notSyncToStateInputs)
  239. }
  240. // update chat list of current conversation
  241. if (!isNewConversation && !conversationIdChangeBecauseOfNew) {
  242. fetchChatList(currConversationId).then((res: any) => {
  243. const { data } = res
  244. const newChatList: IChatItem[] = generateNewChatListWithOpenstatement(notSyncToStateIntroduction, notSyncToStateInputs)
  245. data.forEach((item: any) => {
  246. newChatList.push({
  247. id: `question-${item.id}`,
  248. content: item.query,
  249. isAnswer: false,
  250. })
  251. newChatList.push({
  252. ...item,
  253. id: item.id,
  254. content: item.answer,
  255. feedback: item.feedback,
  256. isAnswer: true,
  257. })
  258. })
  259. setChatList(newChatList)
  260. setErrorHappened(false)
  261. })
  262. }
  263. if (isNewConversation) {
  264. setChatList(generateNewChatListWithOpenstatement())
  265. setErrorHappened(false)
  266. }
  267. setControlFocus(Date.now())
  268. }
  269. useEffect(() => {
  270. handleConversationSwitch()
  271. }, [currConversationId, inited])
  272. const handleConversationIdChange = (id: string) => {
  273. if (id === '-1') {
  274. createNewChat()
  275. setConversationIdChangeBecauseOfNew(true)
  276. }
  277. else {
  278. setConversationIdChangeBecauseOfNew(false)
  279. }
  280. // trigger handleConversationSwitch
  281. setCurrConversationId(id, APP_ID)
  282. setIsShowSuggestion(false)
  283. hideSidebar()
  284. }
  285. /*
  286. * chat info. chat is under conversation.
  287. */
  288. const [chatList, setChatList, getChatList] = useGetState<IChatItem[]>([])
  289. const chatListDomRef = useRef<HTMLDivElement>(null)
  290. useEffect(() => {
  291. // scroll to bottom
  292. if (chatListDomRef.current)
  293. chatListDomRef.current.scrollTop = chatListDomRef.current.scrollHeight
  294. }, [chatList, currConversationId])
  295. // user can not edit inputs if user had send message
  296. const createNewChat = async () => {
  297. // if new chat is already exist, do not create new chat
  298. abortController?.abort()
  299. setResponsingFalse()
  300. if (conversationList.some(item => item.id === '-1'))
  301. return
  302. setConversationList(produce(conversationList, (draft) => {
  303. draft.unshift({
  304. id: '-1',
  305. name: t('share.chat.newChatDefaultName'),
  306. inputs: newConversationInputs,
  307. introduction: conversationIntroduction,
  308. })
  309. }))
  310. configSetDefaultValue()
  311. }
  312. // sometime introduction is not applied to state
  313. const generateNewChatListWithOpenstatement = (introduction?: string, inputs?: Record<string, any> | null) => {
  314. let caculatedIntroduction = introduction || conversationIntroduction || ''
  315. const caculatedPromptVariables = inputs || currInputs || null
  316. if (caculatedIntroduction && caculatedPromptVariables)
  317. caculatedIntroduction = replaceStringWithValues(caculatedIntroduction, promptConfig?.prompt_variables || [], caculatedPromptVariables)
  318. const openstatement = {
  319. id: `${Date.now()}`,
  320. content: caculatedIntroduction,
  321. isAnswer: true,
  322. feedbackDisabled: true,
  323. isOpeningStatement: true,
  324. }
  325. if (caculatedIntroduction)
  326. return [openstatement]
  327. return []
  328. }
  329. const fetchAllConversations = () => {
  330. return fetchConversations(undefined, undefined, 100)
  331. }
  332. const fetchInitData = async () => {
  333. return Promise.all([fetchAllConversations(), fetchAppParams()])
  334. }
  335. // init
  336. useEffect(() => {
  337. (async () => {
  338. try {
  339. const [conversationData, appParams]: any = await fetchInitData()
  340. const prompt_template = ''
  341. // handle current conversation id
  342. const { data: allConversations } = conversationData as { data: ConversationItem[]; has_more: boolean }
  343. const _conversationId = getConversationIdFromStorage(APP_ID)
  344. const isNotNewConversation = allConversations.some(item => item.id === _conversationId)
  345. setAllConversationList(allConversations)
  346. // fetch new conversation info
  347. const { user_input_form, opening_statement: introduction, suggested_questions_after_answer, speech_to_text }: any = appParams
  348. const prompt_variables = userInputsFormToPromptVariables(user_input_form)
  349. setNewConversationInfo({
  350. name: t('share.chat.newChatDefaultName'),
  351. introduction,
  352. })
  353. setPromptConfig({
  354. prompt_template,
  355. prompt_variables,
  356. } as PromptConfig)
  357. setSuggestedQuestionsAfterAnswerConfig(suggested_questions_after_answer)
  358. setSpeechToTextConfig(speech_to_text)
  359. if (isNotNewConversation)
  360. setCurrConversationId(_conversationId, APP_ID, false)
  361. setInited(true)
  362. }
  363. catch (e: any) {
  364. if (e.status === 404) {
  365. setAppUnavailable(true)
  366. }
  367. else {
  368. setIsUnknwonReason(true)
  369. setAppUnavailable(true)
  370. }
  371. }
  372. })()
  373. }, [])
  374. const [isResponsing, { setTrue: setResponsingTrue, setFalse: setResponsingFalse }] = useBoolean(false)
  375. const [abortController, setAbortController] = useState<AbortController | null>(null)
  376. const { notify } = useContext(ToastContext)
  377. const logError = (message: string) => {
  378. notify({ type: 'error', message })
  379. }
  380. const checkCanSend = () => {
  381. if (currConversationId !== '-1')
  382. return true
  383. const prompt_variables = promptConfig?.prompt_variables
  384. const inputs = currInputs
  385. if (!inputs || !prompt_variables || prompt_variables?.length === 0)
  386. return true
  387. let hasEmptyInput = false
  388. const requiredVars = prompt_variables?.filter(({ key, name, required }) => {
  389. const res = (!key || !key.trim()) || (!name || !name.trim()) || (required || required === undefined || required === null)
  390. return res
  391. }) || [] // compatible with old version
  392. requiredVars.forEach(({ key }) => {
  393. if (hasEmptyInput)
  394. return
  395. if (!inputs?.[key])
  396. hasEmptyInput = true
  397. })
  398. if (hasEmptyInput) {
  399. logError(t('appDebug.errorMessage.valueOfVarRequired'))
  400. return false
  401. }
  402. return !hasEmptyInput
  403. }
  404. const [controlFocus, setControlFocus] = useState(0)
  405. const [isShowSuggestion, setIsShowSuggestion] = useState(false)
  406. const doShowSuggestion = isShowSuggestion && !isResponsing
  407. const [suggestQuestions, setSuggestQuestions] = useState<string[]>([])
  408. const [messageTaskId, setMessageTaskId] = useState('')
  409. const [hasStopResponded, setHasStopResponded, getHasStopResponded] = useGetState(false)
  410. const [errorHappened, setErrorHappened] = useState(false)
  411. const [isResponsingConIsCurrCon, setIsResponsingConCurrCon, getIsResponsingConIsCurrCon] = useGetState(true)
  412. const handleSend = async (message: string) => {
  413. if (isNewConversation) {
  414. const isModelSelected = modelId && !!agentThoughtModelList.find(item => item.model_name === modelId)
  415. if (!isModelSelected) {
  416. notify({ type: 'error', message: t('appDebug.errorMessage.notSelectModel') })
  417. return
  418. }
  419. setPrevConfig({
  420. modelId,
  421. providerName,
  422. plugin: plugins as any,
  423. })
  424. }
  425. if (isResponsing) {
  426. notify({ type: 'info', message: t('appDebug.errorMessage.waitForResponse') })
  427. return
  428. }
  429. const formattedPlugins = Object.keys(plugins).map(key => ({
  430. [key]: {
  431. enabled: plugins[key],
  432. },
  433. }))
  434. const formattedDataSets = dataSets.map(({ id }) => {
  435. return {
  436. dataset: {
  437. enabled: true,
  438. id,
  439. },
  440. }
  441. })
  442. const data = {
  443. query: message,
  444. conversation_id: isNewConversation ? null : currConversationId,
  445. model: modelId,
  446. provider: providerName,
  447. tools: [...formattedPlugins, ...formattedDataSets],
  448. }
  449. // qustion
  450. const questionId = `question-${Date.now()}`
  451. const questionItem = {
  452. id: questionId,
  453. content: message,
  454. agent_thoughts: [],
  455. isAnswer: false,
  456. }
  457. const placeholderAnswerId = `answer-placeholder-${Date.now()}`
  458. const placeholderAnswerItem = {
  459. id: placeholderAnswerId,
  460. content: '',
  461. isAnswer: true,
  462. }
  463. const newList = [...getChatList(), questionItem, placeholderAnswerItem]
  464. setChatList(newList)
  465. // answer
  466. const responseItem: IChatItem = {
  467. id: `${Date.now()}`,
  468. content: '',
  469. agent_thoughts: [],
  470. isAnswer: true,
  471. }
  472. const prevTempNewConversationId = getCurrConversationId() || '-1'
  473. let tempNewConversationId = prevTempNewConversationId
  474. setHasStopResponded(false)
  475. setResponsingTrue()
  476. setErrorHappened(false)
  477. setIsShowSuggestion(false)
  478. setIsResponsingConCurrCon(true)
  479. sendChatMessage(data, {
  480. getAbortController: (abortController) => {
  481. setAbortController(abortController)
  482. },
  483. onData: (message: string, isFirstMessage: boolean, { conversationId: newConversationId, messageId, taskId }: any) => {
  484. responseItem.content = responseItem.content + message
  485. responseItem.id = messageId
  486. if (isFirstMessage && newConversationId)
  487. tempNewConversationId = newConversationId
  488. setMessageTaskId(taskId)
  489. // has switched to other conversation
  490. if (prevTempNewConversationId !== getCurrConversationId()) {
  491. setIsResponsingConCurrCon(false)
  492. return
  493. }
  494. // closesure new list is outdated.
  495. const newListWithAnswer = produce(
  496. getChatList().filter(item => item.id !== responseItem.id && item.id !== placeholderAnswerId),
  497. (draft) => {
  498. if (!draft.find(item => item.id === questionId))
  499. draft.push({ ...questionItem } as any)
  500. draft.push({ ...responseItem })
  501. })
  502. setChatList(newListWithAnswer)
  503. },
  504. async onCompleted(hasError?: boolean) {
  505. if (hasError) {
  506. setResponsingFalse()
  507. return
  508. }
  509. if (getConversationIdChangeBecauseOfNew()) {
  510. const { data: allConversations }: any = await fetchAllConversations()
  511. setAllConversationList(allConversations)
  512. noticeUpdateList()
  513. }
  514. setConversationIdChangeBecauseOfNew(false)
  515. resetNewConversationInputs()
  516. setCurrConversationId(tempNewConversationId, APP_ID, true)
  517. if (getIsResponsingConIsCurrCon() && suggestedQuestionsAfterAnswerConfig?.enabled && !getHasStopResponded()) {
  518. const { data }: any = await fetchSuggestedQuestions(responseItem.id)
  519. setSuggestQuestions(data)
  520. setIsShowSuggestion(true)
  521. }
  522. setResponsingFalse()
  523. },
  524. onThought(thought) {
  525. // thought finished then start to return message. Warning: use push agent_thoughts.push would caused problem when the thought is more then 2
  526. responseItem.id = thought.message_id;
  527. (responseItem as any).agent_thoughts = [...(responseItem as any).agent_thoughts, thought] // .push(thought)
  528. // has switched to other conversation
  529. if (prevTempNewConversationId !== getCurrConversationId()) {
  530. setIsResponsingConCurrCon(false)
  531. return
  532. }
  533. const newListWithAnswer = produce(
  534. getChatList().filter(item => item.id !== responseItem.id && item.id !== placeholderAnswerId),
  535. (draft) => {
  536. if (!draft.find(item => item.id === questionId))
  537. draft.push({ ...questionItem })
  538. draft.push({ ...responseItem })
  539. })
  540. setChatList(newListWithAnswer)
  541. },
  542. onError() {
  543. setErrorHappened(true)
  544. // role back placeholder answer
  545. setChatList(produce(getChatList(), (draft) => {
  546. draft.splice(draft.findIndex(item => item.id === placeholderAnswerId), 1)
  547. }))
  548. setResponsingFalse()
  549. },
  550. })
  551. }
  552. const handleFeedback = async (messageId: string, feedback: Feedbacktype) => {
  553. await updateFeedback({ url: `/messages/${messageId}/feedbacks`, body: { rating: feedback.rating } })
  554. const newChatList = chatList.map((item) => {
  555. if (item.id === messageId) {
  556. return {
  557. ...item,
  558. feedback,
  559. }
  560. }
  561. return item
  562. })
  563. setChatList(newChatList)
  564. notify({ type: 'success', message: t('common.api.success') })
  565. }
  566. const [controlChatUpdateAllConversation, setControlChatUpdateAllConversation] = useState(0)
  567. useEffect(() => {
  568. (async () => {
  569. if (controlChatUpdateAllConversation && !isNewConversation) {
  570. const { data: allConversations } = await fetchAllConversations() as { data: ConversationItem[]; has_more: boolean }
  571. const item = allConversations.find(item => item.id === currConversationId)
  572. setAllConversationList(allConversations)
  573. if (item) {
  574. setExistConversationInfo({
  575. ...existConversationInfo,
  576. name: item?.name || '',
  577. } as any)
  578. }
  579. }
  580. })()
  581. }, [controlChatUpdateAllConversation])
  582. const renderSidebar = () => {
  583. if (!APP_ID || !promptConfig)
  584. return null
  585. return (
  586. <Sidebar
  587. list={conversationList}
  588. onListChanged={(list) => {
  589. setConversationList(list)
  590. setControlChatUpdateAllConversation(Date.now())
  591. }}
  592. isClearConversationList={isClearConversationList}
  593. pinnedList={pinnedConversationList}
  594. onPinnedListChanged={(list) => {
  595. setPinnedConversationList(list)
  596. setControlChatUpdateAllConversation(Date.now())
  597. }}
  598. isClearPinnedConversationList={isClearPinnedConversationList}
  599. onMoreLoaded={onMoreLoaded}
  600. onPinnedMoreLoaded={onPinnedMoreLoaded}
  601. isNoMore={!hasMore}
  602. isPinnedNoMore={!hasPinnedMore}
  603. onCurrentIdChange={handleConversationIdChange}
  604. currentId={currConversationId}
  605. copyRight={''}
  606. isInstalledApp={false}
  607. isUniversalChat
  608. installedAppId={''}
  609. siteInfo={siteInfo}
  610. onPin={handlePin}
  611. onUnpin={handleUnpin}
  612. controlUpdateList={controlUpdateConversationList}
  613. onDelete={handleDelete}
  614. />
  615. )
  616. }
  617. const initConfig = getInitConfig('model')
  618. const [modelId, setModeId] = useState<string>((initConfig as any)?.modelId as string)
  619. const [providerName, setProviderName] = useState<ProviderEnum>((initConfig as any)?.providerName as ProviderEnum)
  620. // const currModel = MODEL_LIST.find(item => item.id === modelId)
  621. const [plugins, setPlugins] = useState<Record<string, boolean>>(getInitConfig('plugin') as Record<string, boolean>)
  622. const handlePluginsChange = (key: string, value: boolean) => {
  623. setPlugins({
  624. ...plugins,
  625. [key]: value,
  626. })
  627. }
  628. const [dataSets, setDateSets] = useState<DataSet[]>([])
  629. const configSetDefaultValue = () => {
  630. const initConfig = getInitConfig('model')
  631. setModeId((initConfig as any)?.modelId as string)
  632. setProviderName((initConfig as any)?.providerName as ProviderEnum)
  633. setPlugins(getInitConfig('plugin') as any)
  634. setDateSets([])
  635. }
  636. const isCurrConversationPinned = !!pinnedConversationList.find(item => item.id === currConversationId)
  637. const [controlItemOpHide, setControlItemOpHide] = useState(0)
  638. if (appUnavailable)
  639. return <AppUnavailable isUnknwonReason={isUnknwonReason} />
  640. if (!promptConfig)
  641. return <Loading type='app' />
  642. return (
  643. <div className='bg-gray-100'>
  644. <div
  645. className={cn(
  646. 'flex rounded-t-2xl bg-white overflow-hidden rounded-b-2xl',
  647. )}
  648. style={{
  649. boxShadow: '0px 12px 16px -4px rgba(16, 24, 40, 0.08), 0px 4px 6px -2px rgba(16, 24, 40, 0.03)',
  650. }}
  651. >
  652. {/* sidebar */}
  653. {!isMobile && renderSidebar()}
  654. {isMobile && isShowSidebar && (
  655. <div className='fixed inset-0 z-50'
  656. style={{ backgroundColor: 'rgba(35, 56, 118, 0.2)' }}
  657. onClick={hideSidebar}
  658. >
  659. <div className='inline-block' onClick={e => e.stopPropagation()}>
  660. {renderSidebar()}
  661. </div>
  662. </div>
  663. )}
  664. {/* main */}
  665. <div className={cn(
  666. s.installedApp,
  667. 'flex-grow flex flex-col overflow-y-auto',
  668. )
  669. }>
  670. {(!isNewConversation || isResponsing || errorHappened) && (
  671. <div className='mb-5 antialiased font-sans shrink-0 relative mobile:min-h-[48px] tablet:min-h-[64px]'>
  672. <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'>
  673. <div className='text-gray-900'>{conversationName}</div>
  674. <div className='flex items-center shrink-0 ml-2 space-x-2'>
  675. <ConfigSummary
  676. modelId={modelId}
  677. providerName={providerName}
  678. plugins={plugins}
  679. dataSets={dataSets}
  680. />
  681. <div className={cn('flex w-8 h-8 justify-center items-center shrink-0 rounded-lg border border-gray-200')} onClick={e => e.stopPropagation()}>
  682. <ItemOperation
  683. key={controlItemOpHide}
  684. className='!w-8 !h-8'
  685. isPinned={isCurrConversationPinned}
  686. togglePin={() => isCurrConversationPinned ? handleUnpin(currConversationId) : handlePin(currConversationId)}
  687. isShowDelete
  688. onDelete={() => handleDelete(currConversationId)}
  689. />
  690. </div>
  691. </div>
  692. </div>
  693. </div>
  694. )}
  695. <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')}>
  696. <div className={cn('pc:w-[794px] max-w-full mobile:w-full mx-auto h-full overflow-y-auto')} ref={chatListDomRef}>
  697. <Chat
  698. isShowConfigElem={isNewConversation && chatList.length === 0}
  699. configElem={<Init
  700. modelId={modelId}
  701. providerName={providerName}
  702. onModelChange={(modelId, providerName) => {
  703. setModeId(modelId)
  704. setProviderName(providerName)
  705. }}
  706. plugins={plugins}
  707. onPluginChange={handlePluginsChange}
  708. dataSets={dataSets}
  709. onDataSetsChange={setDateSets}
  710. />}
  711. chatList={chatList}
  712. onSend={handleSend}
  713. isHideFeedbackEdit
  714. onFeedback={handleFeedback}
  715. isResponsing={isResponsing}
  716. canStopResponsing={!!messageTaskId && isResponsingConIsCurrCon}
  717. abortResponsing={async () => {
  718. await stopChatMessageResponding(messageTaskId)
  719. setHasStopResponded(true)
  720. setResponsingFalse()
  721. }}
  722. checkCanSend={checkCanSend}
  723. controlFocus={controlFocus}
  724. isShowSuggestion={doShowSuggestion}
  725. suggestionList={suggestQuestions}
  726. isShowSpeechToText={speechToTextConfig?.enabled}
  727. dataSets={dataSets}
  728. />
  729. </div>
  730. </div>
  731. {isShowConfirm && (
  732. <Confirm
  733. title={t('share.chat.deleteConversation.title')}
  734. content={t('share.chat.deleteConversation.content')}
  735. isShow={isShowConfirm}
  736. onClose={hideConfirm}
  737. onConfirm={didDelete}
  738. onCancel={hideConfirm}
  739. />
  740. )}
  741. </div>
  742. </div>
  743. </div>
  744. )
  745. }
  746. export default React.memo(Main)