index.tsx 33 KB

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