index.tsx 27 KB

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