index.tsx 34 KB

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