index.tsx 26 KB

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