index.tsx 32 KB

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