index.tsx 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927
  1. /* eslint-disable @typescript-eslint/no-use-before-define */
  2. 'use client'
  3. import type { FC } from 'react'
  4. import React, { useEffect, useRef, useState } from 'react'
  5. import cn from 'classnames'
  6. import useSWR from 'swr'
  7. import { useTranslation } from 'react-i18next'
  8. import { useContext } from 'use-context-selector'
  9. import produce, { setAutoFreeze } from 'immer'
  10. import { useBoolean, useGetState } from 'ahooks'
  11. import AppUnavailable from '../../base/app-unavailable'
  12. import { checkOrSetAccessToken } from '../utils'
  13. import { addFileInfos, sortAgentSorts } from '../../tools/utils'
  14. import useConversation from './hooks/use-conversation'
  15. import { ToastContext } from '@/app/components/base/toast'
  16. import Sidebar from '@/app/components/share/chat/sidebar'
  17. import ConfigSence from '@/app/components/share/chat/config-scence'
  18. import Header from '@/app/components/share/header'
  19. import {
  20. delConversation,
  21. fetchAppInfo,
  22. fetchAppMeta,
  23. fetchAppParams,
  24. fetchChatList,
  25. fetchConversations,
  26. fetchSuggestedQuestions,
  27. generationConversationName,
  28. pinConversation,
  29. sendChatMessage,
  30. stopChatMessageResponding,
  31. unpinConversation,
  32. updateFeedback,
  33. } from '@/service/share'
  34. import type { AppMeta, ConversationItem, SiteInfo } from '@/models/share'
  35. import type {
  36. CitationConfig,
  37. PromptConfig,
  38. SpeechToTextConfig,
  39. SuggestedQuestionsAfterAnswerConfig,
  40. TextToSpeechConfig,
  41. } from '@/models/debug'
  42. import type { Feedbacktype, IChatItem } from '@/app/components/app/chat/type'
  43. import Chat from '@/app/components/app/chat'
  44. import { changeLanguage } from '@/i18n/i18next-config'
  45. import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'
  46. import Loading from '@/app/components/base/loading'
  47. import { replaceStringWithValues } from '@/app/components/app/configuration/prompt-value-panel'
  48. import { userInputsFormToPromptVariables } from '@/utils/model-config'
  49. import type { InstalledApp } from '@/models/explore'
  50. import Confirm from '@/app/components/base/confirm'
  51. import type { VisionFile, VisionSettings } from '@/types/app'
  52. import { Resolution, TransferMethod } from '@/types/app'
  53. import { fetchFileUploadConfig } from '@/service/common'
  54. import type { Annotation as AnnotationType } from '@/models/log'
  55. export type IMainProps = {
  56. isInstalledApp?: boolean
  57. installedAppInfo?: InstalledApp
  58. isSupportPlugin?: boolean
  59. isUniversalChat?: boolean
  60. }
  61. const Main: FC<IMainProps> = ({
  62. isInstalledApp = false,
  63. installedAppInfo,
  64. }) => {
  65. const { t } = useTranslation()
  66. const media = useBreakpoints()
  67. const isMobile = media === MediaType.mobile
  68. /*
  69. * app info
  70. */
  71. const [appUnavailable, setAppUnavailable] = useState<boolean>(false)
  72. const [isUnknwonReason, setIsUnknwonReason] = useState<boolean>(false)
  73. const [appId, setAppId] = useState<string>('')
  74. const [isPublicVersion, setIsPublicVersion] = useState<boolean>(true)
  75. const [siteInfo, setSiteInfo] = useState<SiteInfo | null>()
  76. const [promptConfig, setPromptConfig] = useState<PromptConfig | null>(null)
  77. const [inited, setInited] = useState<boolean>(false)
  78. const [plan, setPlan] = useState<string>('basic') // basic/plus/pro
  79. const [canReplaceLogo, setCanReplaceLogo] = useState<boolean>(false)
  80. const [customConfig, setCustomConfig] = useState<any>(null)
  81. const [appMeta, setAppMeta] = useState<AppMeta | null>(null)
  82. // in mobile, show sidebar by click button
  83. const [isShowSidebar, { setTrue: showSidebar, setFalse: hideSidebar }] = useBoolean(false)
  84. // Can Use metadata(https://beta.nextjs.org/docs/api-reference/metadata) to set title. But it only works in server side client.
  85. useEffect(() => {
  86. if (siteInfo?.title) {
  87. if (canReplaceLogo)
  88. document.title = `${siteInfo.title}`
  89. else
  90. document.title = `${siteInfo.title} - Powered by Dify`
  91. }
  92. }, [siteInfo?.title, canReplaceLogo])
  93. /*
  94. * conversation info
  95. */
  96. const [allConversationList, setAllConversationList] = useState<ConversationItem[]>([])
  97. const [isClearConversationList, { setTrue: clearConversationListTrue, setFalse: clearConversationListFalse }] = useBoolean(false)
  98. const [isClearPinnedConversationList, { setTrue: clearPinnedConversationListTrue, setFalse: clearPinnedConversationListFalse }] = useBoolean(false)
  99. const {
  100. conversationList,
  101. setConversationList,
  102. pinnedConversationList,
  103. setPinnedConversationList,
  104. currConversationId,
  105. getCurrConversationId,
  106. setCurrConversationId,
  107. getConversationIdFromStorage,
  108. isNewConversation,
  109. currConversationInfo,
  110. currInputs,
  111. newConversationInputs,
  112. // existConversationInputs,
  113. resetNewConversationInputs,
  114. setCurrInputs,
  115. setNewConversationInfo,
  116. existConversationInfo,
  117. setExistConversationInfo,
  118. } = useConversation()
  119. const [suggestedQuestions, setSuggestQuestions] = useState<string[]>([])
  120. const [hasMore, setHasMore] = useState<boolean>(true)
  121. const [hasPinnedMore, setHasPinnedMore] = useState<boolean>(true)
  122. const onMoreLoaded = ({ data: conversations, has_more }: any) => {
  123. setHasMore(has_more)
  124. if (isClearConversationList) {
  125. setConversationList(conversations)
  126. clearConversationListFalse()
  127. }
  128. else {
  129. setConversationList([...conversationList, ...conversations])
  130. }
  131. }
  132. const onPinnedMoreLoaded = ({ data: conversations, has_more }: any) => {
  133. setHasPinnedMore(has_more)
  134. if (isClearPinnedConversationList) {
  135. setPinnedConversationList(conversations)
  136. clearPinnedConversationListFalse()
  137. }
  138. else {
  139. setPinnedConversationList([...pinnedConversationList, ...conversations])
  140. }
  141. }
  142. const [controlUpdateConversationList, setControlUpdateConversationList] = useState(0)
  143. const noticeUpdateList = () => {
  144. setHasMore(true)
  145. clearConversationListTrue()
  146. setHasPinnedMore(true)
  147. clearPinnedConversationListTrue()
  148. setControlUpdateConversationList(Date.now())
  149. }
  150. const handlePin = async (id: string) => {
  151. await pinConversation(isInstalledApp, installedAppInfo?.id, id)
  152. notify({ type: 'success', message: t('common.api.success') })
  153. noticeUpdateList()
  154. }
  155. const handleUnpin = async (id: string) => {
  156. await unpinConversation(isInstalledApp, installedAppInfo?.id, id)
  157. notify({ type: 'success', message: t('common.api.success') })
  158. noticeUpdateList()
  159. }
  160. const [isShowConfirm, { setTrue: showConfirm, setFalse: hideConfirm }] = useBoolean(false)
  161. const [toDeleteConversationId, setToDeleteConversationId] = useState('')
  162. const handleDelete = (id: string) => {
  163. setToDeleteConversationId(id)
  164. hideSidebar() // mobile
  165. showConfirm()
  166. }
  167. const didDelete = async () => {
  168. await delConversation(isInstalledApp, installedAppInfo?.id, toDeleteConversationId)
  169. notify({ type: 'success', message: t('common.api.success') })
  170. hideConfirm()
  171. if (currConversationId === toDeleteConversationId)
  172. handleConversationIdChange('-1')
  173. noticeUpdateList()
  174. }
  175. const [suggestedQuestionsAfterAnswerConfig, setSuggestedQuestionsAfterAnswerConfig] = useState<SuggestedQuestionsAfterAnswerConfig | null>(null)
  176. const [speechToTextConfig, setSpeechToTextConfig] = useState<SpeechToTextConfig | null>(null)
  177. const [textToSpeechConfig, setTextToSpeechConfig] = useState<TextToSpeechConfig | null>(null)
  178. const [citationConfig, setCitationConfig] = useState<CitationConfig | null>(null)
  179. const [conversationIdChangeBecauseOfNew, setConversationIdChangeBecauseOfNew, getConversationIdChangeBecauseOfNew] = useGetState(false)
  180. const [isChatStarted, { setTrue: setChatStarted, setFalse: setChatNotStarted }] = useBoolean(false)
  181. const handleStartChat = (inputs: Record<string, any>) => {
  182. createNewChat()
  183. setConversationIdChangeBecauseOfNew(true)
  184. setCurrInputs(inputs)
  185. setChatStarted()
  186. // parse variables in introduction
  187. setChatList(generateNewChatListWithOpenstatement('', inputs))
  188. }
  189. const hasSetInputs = (() => {
  190. if (!isNewConversation)
  191. return true
  192. return isChatStarted
  193. })()
  194. const conversationName = currConversationInfo?.name || t('share.chat.newChatDefaultName') as string
  195. const conversationIntroduction = currConversationInfo?.introduction || ''
  196. const [controlChatUpdateAllConversation, setControlChatUpdateAllConversation] = useState(0)
  197. // onData change thought (the produce obj). https://github.com/immerjs/immer/issues/576
  198. useEffect(() => {
  199. setAutoFreeze(false)
  200. return () => {
  201. setAutoFreeze(true)
  202. }
  203. }, [])
  204. useEffect(() => {
  205. (async () => {
  206. if (controlChatUpdateAllConversation && !isNewConversation) {
  207. const { data: allConversations } = await fetchAllConversations() as { data: ConversationItem[]; has_more: boolean }
  208. const item = allConversations.find(item => item.id === currConversationId)
  209. setAllConversationList(allConversations)
  210. if (item) {
  211. setExistConversationInfo({
  212. ...existConversationInfo,
  213. name: item?.name || '',
  214. } as any)
  215. }
  216. }
  217. })()
  218. }, [controlChatUpdateAllConversation])
  219. const handleConversationSwitch = () => {
  220. if (!inited)
  221. return
  222. if (!appId) {
  223. // wait for appId
  224. setTimeout(handleConversationSwitch, 100)
  225. return
  226. }
  227. // update inputs of current conversation
  228. let notSyncToStateIntroduction = ''
  229. let notSyncToStateInputs: Record<string, any> | undefined | null = {}
  230. if (!isNewConversation) {
  231. const item = allConversationList.find(item => item.id === currConversationId)
  232. notSyncToStateInputs = item?.inputs || {}
  233. setCurrInputs(notSyncToStateInputs)
  234. notSyncToStateIntroduction = item?.introduction || ''
  235. setExistConversationInfo({
  236. name: item?.name || '',
  237. introduction: notSyncToStateIntroduction,
  238. })
  239. }
  240. else {
  241. notSyncToStateInputs = newConversationInputs
  242. setCurrInputs(notSyncToStateInputs)
  243. }
  244. // update chat list of current conversation
  245. if (!isNewConversation && !conversationIdChangeBecauseOfNew) {
  246. fetchChatList(currConversationId, isInstalledApp, installedAppInfo?.id).then((res: any) => {
  247. const { data } = res
  248. const newChatList: IChatItem[] = generateNewChatListWithOpenstatement(notSyncToStateIntroduction, notSyncToStateInputs)
  249. data.forEach((item: any) => {
  250. newChatList.push({
  251. id: `question-${item.id}`,
  252. content: item.query,
  253. isAnswer: false,
  254. message_files: item.message_files?.filter((file: any) => file.belongs_to === 'user') || [],
  255. })
  256. newChatList.push({
  257. id: item.id,
  258. content: item.answer,
  259. agent_thoughts: addFileInfos(item.agent_thoughts ? sortAgentSorts(item.agent_thoughts) : item.agent_thoughts, item.message_files),
  260. feedback: item.feedback,
  261. isAnswer: true,
  262. citation: item.retriever_resources,
  263. message_files: item.message_files?.filter((file: any) => file.belongs_to === 'assistant') || [],
  264. })
  265. })
  266. setChatList(newChatList)
  267. })
  268. }
  269. if (isNewConversation && isChatStarted)
  270. setChatList(generateNewChatListWithOpenstatement())
  271. setControlFocus(Date.now())
  272. }
  273. useEffect(handleConversationSwitch, [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, appId)
  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 canEditInpus = !chatList.some(item => item.isAnswer === false) && isNewConversation
  299. const createNewChat = async () => {
  300. // if new chat is already exist, do not create new chat
  301. abortController?.abort()
  302. setResponsingFalse()
  303. if (conversationList.some(item => item.id === '-1'))
  304. return
  305. setConversationList(produce(conversationList, (draft) => {
  306. draft.unshift({
  307. id: '-1',
  308. name: t('share.chat.newChatDefaultName'),
  309. inputs: newConversationInputs,
  310. introduction: conversationIntroduction,
  311. })
  312. }))
  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. suggestedQuestions: openingSuggestedQuestions,
  327. }
  328. if (caculatedIntroduction)
  329. return [openstatement]
  330. return []
  331. }
  332. const fetchAllConversations = () => {
  333. return fetchConversations(isInstalledApp, installedAppInfo?.id, undefined, undefined, 100)
  334. }
  335. const fetchInitData = async () => {
  336. if (!isInstalledApp)
  337. await checkOrSetAccessToken()
  338. return Promise.all([isInstalledApp
  339. ? {
  340. app_id: installedAppInfo?.id,
  341. site: {
  342. title: installedAppInfo?.app.name,
  343. icon: installedAppInfo?.app.icon,
  344. icon_background: installedAppInfo?.app.icon_background,
  345. prompt_public: false,
  346. copyright: '',
  347. },
  348. plan: 'basic',
  349. }
  350. : fetchAppInfo(), fetchAllConversations(), fetchAppParams(isInstalledApp, installedAppInfo?.id), fetchAppMeta(isInstalledApp, installedAppInfo?.id)])
  351. }
  352. const { data: fileUploadConfigResponse } = useSWR(isInstalledApp ? { url: '/files/upload' } : null, fetchFileUploadConfig)
  353. // init
  354. useEffect(() => {
  355. (async () => {
  356. try {
  357. const [appData, conversationData, appParams, appMeta]: any = await fetchInitData()
  358. setAppMeta(appMeta)
  359. const { app_id: appId, site: siteInfo, plan, can_replace_logo, custom_config }: any = appData
  360. setAppId(appId)
  361. setPlan(plan)
  362. setCanReplaceLogo(can_replace_logo)
  363. setCustomConfig(custom_config)
  364. const tempIsPublicVersion = siteInfo.prompt_public
  365. setIsPublicVersion(tempIsPublicVersion)
  366. const prompt_template = ''
  367. // handle current conversation id
  368. const { data: allConversations } = conversationData as { data: ConversationItem[]; has_more: boolean }
  369. const _conversationId = getConversationIdFromStorage(appId)
  370. const isNotNewConversation = allConversations.some(item => item.id === _conversationId)
  371. setAllConversationList(allConversations)
  372. // fetch new conversation info
  373. const { user_input_form, opening_statement: introduction, suggested_questions, suggested_questions_after_answer, speech_to_text, text_to_speech, retriever_resource, file_upload, sensitive_word_avoidance }: any = appParams
  374. setVisionConfig({
  375. ...file_upload.image,
  376. image_file_size_limit: appParams?.system_parameters?.image_file_size_limit,
  377. })
  378. const prompt_variables = userInputsFormToPromptVariables(user_input_form)
  379. if (siteInfo.default_language)
  380. changeLanguage(siteInfo.default_language)
  381. setNewConversationInfo({
  382. name: t('share.chat.newChatDefaultName'),
  383. introduction,
  384. })
  385. setOpeningSuggestedQuestions(suggested_questions || [])
  386. setSiteInfo(siteInfo as SiteInfo)
  387. setPromptConfig({
  388. prompt_template,
  389. prompt_variables,
  390. } as PromptConfig)
  391. setSuggestedQuestionsAfterAnswerConfig(suggested_questions_after_answer)
  392. setSpeechToTextConfig(speech_to_text)
  393. setTextToSpeechConfig(text_to_speech)
  394. setCitationConfig(retriever_resource)
  395. // setConversationList(conversations as ConversationItem[])
  396. if (isNotNewConversation)
  397. setCurrConversationId(_conversationId, appId, false)
  398. setInited(true)
  399. }
  400. catch (e: any) {
  401. if (e.status === 404) {
  402. setAppUnavailable(true)
  403. }
  404. else {
  405. setIsUnknwonReason(true)
  406. setAppUnavailable(true)
  407. }
  408. }
  409. })()
  410. }, [])
  411. const [isResponsing, { setTrue: setResponsingTrue, setFalse: setResponsingFalse }] = useBoolean(false)
  412. const [abortController, setAbortController] = useState<AbortController | null>(null)
  413. const { notify } = useContext(ToastContext)
  414. const logError = (message: string) => {
  415. notify({ type: 'error', message })
  416. }
  417. const checkCanSend = () => {
  418. if (currConversationId !== '-1')
  419. return true
  420. const prompt_variables = promptConfig?.prompt_variables
  421. const inputs = currInputs
  422. if (!inputs || !prompt_variables || prompt_variables?.length === 0)
  423. return true
  424. let hasEmptyInput = ''
  425. const requiredVars = prompt_variables?.filter(({ key, name, required }) => {
  426. const res = (!key || !key.trim()) || (!name || !name.trim()) || (required || required === undefined || required === null)
  427. return res
  428. }) || [] // compatible with old version
  429. requiredVars.forEach(({ key, name }) => {
  430. if (hasEmptyInput)
  431. return
  432. if (!inputs?.[key])
  433. hasEmptyInput = name
  434. })
  435. if (hasEmptyInput) {
  436. logError(t('appDebug.errorMessage.valueOfVarRequired', { key: hasEmptyInput }))
  437. return false
  438. }
  439. return !hasEmptyInput
  440. }
  441. const [controlFocus, setControlFocus] = useState(0)
  442. const [isShowSuggestion, setIsShowSuggestion] = useState(false)
  443. const doShowSuggestion = isShowSuggestion && !isResponsing
  444. const [openingSuggestedQuestions, setOpeningSuggestedQuestions] = useState<string[]>([])
  445. const [messageTaskId, setMessageTaskId] = useState('')
  446. const [hasStopResponded, setHasStopResponded, getHasStopResponded] = useGetState(false)
  447. const [isResponsingConIsCurrCon, setIsResponsingConCurrCon, getIsResponsingConIsCurrCon] = useGetState(true)
  448. const [userQuery, setUserQuery] = useState('')
  449. const [visionConfig, setVisionConfig] = useState<VisionSettings>({
  450. enabled: false,
  451. number_limits: 2,
  452. detail: Resolution.low,
  453. transfer_methods: [TransferMethod.local_file],
  454. })
  455. const updateCurrentQA = ({
  456. responseItem,
  457. questionId,
  458. placeholderAnswerId,
  459. questionItem,
  460. }: {
  461. responseItem: IChatItem
  462. questionId: string
  463. placeholderAnswerId: string
  464. questionItem: IChatItem
  465. }) => {
  466. // closesure new list is outdated.
  467. const newListWithAnswer = produce(
  468. getChatList().filter(item => item.id !== responseItem.id && item.id !== placeholderAnswerId),
  469. (draft) => {
  470. if (!draft.find(item => item.id === questionId))
  471. draft.push({ ...questionItem })
  472. draft.push({ ...responseItem })
  473. })
  474. setChatList(newListWithAnswer)
  475. }
  476. const handleSend = async (message: string, files?: VisionFile[]) => {
  477. if (isResponsing) {
  478. notify({ type: 'info', message: t('appDebug.errorMessage.waitForResponse') })
  479. return
  480. }
  481. if (files?.find(item => item.transfer_method === TransferMethod.local_file && !item.upload_file_id)) {
  482. notify({ type: 'info', message: t('appDebug.errorMessage.waitForImgUpload') })
  483. return false
  484. }
  485. const data: Record<string, any> = {
  486. inputs: currInputs,
  487. query: message,
  488. conversation_id: isNewConversation ? null : currConversationId,
  489. }
  490. if (visionConfig.enabled && files && files?.length > 0) {
  491. data.files = files.map((item) => {
  492. if (item.transfer_method === TransferMethod.local_file) {
  493. return {
  494. ...item,
  495. url: '',
  496. }
  497. }
  498. return item
  499. })
  500. }
  501. // qustion
  502. const questionId = `question-${Date.now()}`
  503. const questionItem = {
  504. id: questionId,
  505. content: message,
  506. isAnswer: false,
  507. message_files: files,
  508. }
  509. const placeholderAnswerId = `answer-placeholder-${Date.now()}`
  510. const placeholderAnswerItem = {
  511. id: placeholderAnswerId,
  512. content: '',
  513. isAnswer: true,
  514. }
  515. const newList = [...getChatList(), questionItem, placeholderAnswerItem]
  516. setChatList(newList)
  517. let isAgentMode = false
  518. // answer
  519. const responseItem: IChatItem = {
  520. id: `${Date.now()}`,
  521. content: '',
  522. agent_thoughts: [],
  523. message_files: [],
  524. isAnswer: true,
  525. }
  526. let hasSetResponseId = false
  527. const prevTempNewConversationId = getCurrConversationId() || '-1'
  528. let tempNewConversationId = prevTempNewConversationId
  529. setHasStopResponded(false)
  530. setResponsingTrue()
  531. setIsShowSuggestion(false)
  532. setIsResponsingConCurrCon(true)
  533. sendChatMessage(data, {
  534. getAbortController: (abortController) => {
  535. setAbortController(abortController)
  536. },
  537. onData: (message: string, isFirstMessage: boolean, { conversationId: newConversationId, messageId, taskId }: any) => {
  538. if (!isAgentMode) {
  539. responseItem.content = responseItem.content + message
  540. }
  541. else {
  542. const lastThought = responseItem.agent_thoughts?.[responseItem.agent_thoughts?.length - 1]
  543. if (lastThought)
  544. lastThought.thought = lastThought.thought + message // need immer setAutoFreeze
  545. }
  546. if (messageId && !hasSetResponseId) {
  547. responseItem.id = messageId
  548. hasSetResponseId = true
  549. }
  550. if (isFirstMessage && newConversationId)
  551. tempNewConversationId = newConversationId
  552. setMessageTaskId(taskId)
  553. // has switched to other conversation
  554. if (prevTempNewConversationId !== getCurrConversationId()) {
  555. setIsResponsingConCurrCon(false)
  556. return
  557. }
  558. updateCurrentQA({
  559. responseItem,
  560. questionId,
  561. placeholderAnswerId,
  562. questionItem,
  563. })
  564. },
  565. async onCompleted(hasError?: boolean) {
  566. if (hasError)
  567. return
  568. if (getConversationIdChangeBecauseOfNew()) {
  569. const { data: allConversations }: any = await fetchAllConversations()
  570. const newItem: any = await generationConversationName(isInstalledApp, installedAppInfo?.id, allConversations[0].id)
  571. const newAllConversations = produce(allConversations, (draft: any) => {
  572. draft[0].name = newItem.name
  573. })
  574. setAllConversationList(newAllConversations as any)
  575. noticeUpdateList()
  576. }
  577. setConversationIdChangeBecauseOfNew(false)
  578. resetNewConversationInputs()
  579. setChatNotStarted()
  580. setCurrConversationId(tempNewConversationId, appId, true)
  581. if (getIsResponsingConIsCurrCon() && suggestedQuestionsAfterAnswerConfig?.enabled && !getHasStopResponded()) {
  582. const { data }: any = await fetchSuggestedQuestions(responseItem.id, isInstalledApp, installedAppInfo?.id)
  583. setSuggestQuestions(data)
  584. setIsShowSuggestion(true)
  585. }
  586. setResponsingFalse()
  587. },
  588. onFile(file) {
  589. const lastThought = responseItem.agent_thoughts?.[responseItem.agent_thoughts?.length - 1]
  590. if (lastThought)
  591. lastThought.message_files = [...(lastThought as any).message_files, { ...file }]
  592. updateCurrentQA({
  593. responseItem,
  594. questionId,
  595. placeholderAnswerId,
  596. questionItem,
  597. })
  598. },
  599. onThought(thought) {
  600. // console.log(`${thought.id};${thought.thought};${thought.tool};${thought.tool_input}`)
  601. isAgentMode = true
  602. const response = responseItem as any
  603. if (thought.message_id && !hasSetResponseId) {
  604. response.id = thought.message_id
  605. hasSetResponseId = true
  606. }
  607. // responseItem.id = thought.message_id;
  608. if (response.agent_thoughts.length === 0) {
  609. response.agent_thoughts.push(thought)
  610. }
  611. else {
  612. const lastThought = response.agent_thoughts[response.agent_thoughts.length - 1]
  613. // thought changed but still the same thought, so update.
  614. if (lastThought.id === thought.id) {
  615. thought.thought = lastThought.thought
  616. thought.message_files = lastThought.message_files
  617. responseItem.agent_thoughts![response.agent_thoughts.length - 1] = thought
  618. }
  619. else {
  620. responseItem.agent_thoughts!.push(thought)
  621. }
  622. }
  623. // has switched to other conversation
  624. if (prevTempNewConversationId !== getCurrConversationId()) {
  625. setIsResponsingConCurrCon(false)
  626. return false
  627. }
  628. updateCurrentQA({
  629. responseItem,
  630. questionId,
  631. placeholderAnswerId,
  632. questionItem,
  633. })
  634. },
  635. onMessageEnd: (messageEnd) => {
  636. if (messageEnd.metadata?.annotation_reply) {
  637. responseItem.id = messageEnd.id
  638. responseItem.annotation = ({
  639. id: messageEnd.metadata.annotation_reply.id,
  640. authorName: messageEnd.metadata.annotation_reply.account.name,
  641. } as AnnotationType)
  642. const newListWithAnswer = produce(
  643. getChatList().filter(item => item.id !== responseItem.id && item.id !== placeholderAnswerId),
  644. (draft) => {
  645. if (!draft.find(item => item.id === questionId))
  646. draft.push({ ...questionItem })
  647. draft.push({
  648. ...responseItem,
  649. })
  650. })
  651. setChatList(newListWithAnswer)
  652. return
  653. }
  654. // not support show citation
  655. // responseItem.citation = messageEnd.retriever_resources
  656. if (!isInstalledApp)
  657. return
  658. const newListWithAnswer = produce(
  659. getChatList().filter(item => item.id !== responseItem.id && item.id !== placeholderAnswerId),
  660. (draft) => {
  661. if (!draft.find(item => item.id === questionId))
  662. draft.push({ ...questionItem })
  663. draft.push({ ...responseItem })
  664. })
  665. setChatList(newListWithAnswer)
  666. },
  667. onMessageReplace: (messageReplace) => {
  668. if (isInstalledApp) {
  669. responseItem.content = messageReplace.answer
  670. }
  671. else {
  672. setChatList(produce(
  673. getChatList(),
  674. (draft) => {
  675. const current = draft.find(item => item.id === messageReplace.id)
  676. if (current)
  677. current.content = messageReplace.answer
  678. },
  679. ))
  680. }
  681. },
  682. onError() {
  683. setResponsingFalse()
  684. // role back placeholder answer
  685. setChatList(produce(getChatList(), (draft) => {
  686. draft.splice(draft.findIndex(item => item.id === placeholderAnswerId), 1)
  687. }))
  688. },
  689. }, isInstalledApp, installedAppInfo?.id)
  690. }
  691. const handleFeedback = async (messageId: string, feedback: Feedbacktype) => {
  692. await updateFeedback({ url: `/messages/${messageId}/feedbacks`, body: { rating: feedback.rating } }, isInstalledApp, installedAppInfo?.id)
  693. const newChatList = chatList.map((item) => {
  694. if (item.id === messageId) {
  695. return {
  696. ...item,
  697. feedback,
  698. }
  699. }
  700. return item
  701. })
  702. setChatList(newChatList)
  703. notify({ type: 'success', message: t('common.api.success') })
  704. }
  705. const renderSidebar = () => {
  706. if (!appId || !siteInfo || !promptConfig)
  707. return null
  708. return (
  709. <Sidebar
  710. list={conversationList}
  711. onListChanged={(list) => {
  712. setConversationList(list)
  713. setControlChatUpdateAllConversation(Date.now())
  714. }}
  715. isClearConversationList={isClearConversationList}
  716. pinnedList={pinnedConversationList}
  717. onPinnedListChanged={(list) => {
  718. setPinnedConversationList(list)
  719. setControlChatUpdateAllConversation(Date.now())
  720. }}
  721. isClearPinnedConversationList={isClearPinnedConversationList}
  722. onMoreLoaded={onMoreLoaded}
  723. onPinnedMoreLoaded={onPinnedMoreLoaded}
  724. isNoMore={!hasMore}
  725. isPinnedNoMore={!hasPinnedMore}
  726. onCurrentIdChange={handleConversationIdChange}
  727. currentId={currConversationId}
  728. copyRight={siteInfo.copyright || siteInfo.title}
  729. isInstalledApp={isInstalledApp}
  730. installedAppId={installedAppInfo?.id}
  731. siteInfo={siteInfo}
  732. onPin={handlePin}
  733. onUnpin={handleUnpin}
  734. controlUpdateList={controlUpdateConversationList}
  735. onDelete={handleDelete}
  736. onStartChat={() => handleConversationIdChange('-1')}
  737. />
  738. )
  739. }
  740. if (appUnavailable)
  741. return <AppUnavailable isUnknwonReason={isUnknwonReason} />
  742. if (!appId || !siteInfo || !promptConfig) {
  743. return <div className='flex h-screen w-full'>
  744. <Loading type='app' />
  745. </div>
  746. }
  747. return (
  748. <div className='bg-gray-100 h-full flex flex-col'>
  749. {!isInstalledApp && (
  750. <Header
  751. title={siteInfo.title}
  752. icon={siteInfo.icon || ''}
  753. icon_background={siteInfo.icon_background}
  754. isMobile={isMobile}
  755. onShowSideBar={showSidebar}
  756. onCreateNewChat={() => handleConversationIdChange('-1')}
  757. />
  758. )}
  759. <div
  760. className={cn(
  761. 'flex rounded-t-2xl bg-white overflow-hidden h-full w-full',
  762. isInstalledApp && 'rounded-b-2xl',
  763. )}
  764. style={isInstalledApp
  765. ? {
  766. boxShadow: '0px 12px 16px -4px rgba(16, 24, 40, 0.08), 0px 4px 6px -2px rgba(16, 24, 40, 0.03)',
  767. }
  768. : {}}
  769. >
  770. {/* sidebar */}
  771. {!isMobile && renderSidebar()}
  772. {isMobile && isShowSidebar && (
  773. <div className='fixed inset-0 z-50'
  774. style={{ backgroundColor: 'rgba(35, 56, 118, 0.2)' }}
  775. onClick={hideSidebar}
  776. >
  777. <div className='inline-block' onClick={e => e.stopPropagation()}>
  778. {renderSidebar()}
  779. </div>
  780. </div>
  781. )}
  782. {/* main */}
  783. <div className={cn(
  784. 'h-full flex-grow flex flex-col overflow-y-auto',
  785. )
  786. }>
  787. <ConfigSence
  788. conversationName={conversationName}
  789. hasSetInputs={hasSetInputs}
  790. isPublicVersion={isPublicVersion}
  791. siteInfo={siteInfo}
  792. promptConfig={promptConfig}
  793. onStartChat={handleStartChat}
  794. canEidtInpus={canEditInpus}
  795. savedInputs={currInputs as Record<string, any>}
  796. onInputsChange={setCurrInputs}
  797. plan={plan}
  798. canReplaceLogo={canReplaceLogo}
  799. customConfig={customConfig}
  800. ></ConfigSence>
  801. {
  802. hasSetInputs && (
  803. <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')}>
  804. <div className='h-full overflow-y-auto' ref={chatListDomRef}>
  805. <Chat
  806. chatList={chatList}
  807. query={userQuery}
  808. onQueryChange={setUserQuery}
  809. onSend={handleSend}
  810. isHideFeedbackEdit
  811. onFeedback={handleFeedback}
  812. isResponsing={isResponsing}
  813. canStopResponsing={!!messageTaskId && isResponsingConIsCurrCon}
  814. abortResponsing={async () => {
  815. await stopChatMessageResponding(appId, messageTaskId, isInstalledApp, installedAppInfo?.id)
  816. setHasStopResponded(true)
  817. setResponsingFalse()
  818. }}
  819. checkCanSend={checkCanSend}
  820. controlFocus={controlFocus}
  821. isShowSuggestion={doShowSuggestion}
  822. suggestionList={suggestedQuestions}
  823. isShowSpeechToText={speechToTextConfig?.enabled}
  824. isShowTextToSpeech={textToSpeechConfig?.enabled}
  825. isShowCitation={citationConfig?.enabled && isInstalledApp}
  826. visionConfig={{
  827. ...visionConfig,
  828. image_file_size_limit: fileUploadConfigResponse ? fileUploadConfigResponse.image_file_size_limit : visionConfig.image_file_size_limit,
  829. }}
  830. allToolIcons={appMeta?.tool_icons || {}}
  831. />
  832. </div>
  833. </div>)
  834. }
  835. {isShowConfirm && (
  836. <Confirm
  837. title={t('share.chat.deleteConversation.title')}
  838. content={t('share.chat.deleteConversation.content')}
  839. isShow={isShowConfirm}
  840. onClose={hideConfirm}
  841. onConfirm={didDelete}
  842. onCancel={hideConfirm}
  843. />
  844. )}
  845. </div>
  846. </div>
  847. </div>
  848. )
  849. }
  850. export default React.memo(Main)