index.tsx 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  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 { useTranslation } from 'react-i18next'
  7. import { useContext } from 'use-context-selector'
  8. import produce from 'immer'
  9. import { useBoolean, useGetState } from 'ahooks'
  10. import { checkOrSetAccessToken } from '../utils'
  11. import AppUnavailable from '../../base/app-unavailable'
  12. import useConversation from './hooks/use-conversation'
  13. import s from './style.module.css'
  14. import { ToastContext } from '@/app/components/base/toast'
  15. import ConfigScene from '@/app/components/share/chatbot/config-scence'
  16. import Header from '@/app/components/share/header'
  17. import { fetchAppInfo, fetchAppParams, fetchChatList, fetchConversations, fetchSuggestedQuestions, sendChatMessage, stopChatMessageResponding, updateFeedback } from '@/service/share'
  18. import type { ConversationItem, SiteInfo } from '@/models/share'
  19. import type { PromptConfig, SuggestedQuestionsAfterAnswerConfig } from '@/models/debug'
  20. import type { Feedbacktype, IChatItem } from '@/app/components/app/chat/type'
  21. import Chat from '@/app/components/app/chat'
  22. import { changeLanguage } from '@/i18n/i18next-config'
  23. import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'
  24. import Loading from '@/app/components/base/loading'
  25. import { replaceStringWithValues } from '@/app/components/app/configuration/prompt-value-panel'
  26. import { userInputsFormToPromptVariables } from '@/utils/model-config'
  27. import type { InstalledApp } from '@/models/explore'
  28. import { AlertTriangle } from '@/app/components/base/icons/src/vender/solid/alertsAndFeedback'
  29. import LogoHeader from '@/app/components/base/logo/logo-embeded-chat-header'
  30. import LogoAvatar from '@/app/components/base/logo/logo-embeded-chat-avatar'
  31. export type IMainProps = {
  32. isInstalledApp?: boolean
  33. installedAppInfo?: InstalledApp
  34. }
  35. const Main: FC<IMainProps> = ({
  36. isInstalledApp = false,
  37. installedAppInfo,
  38. }) => {
  39. const { t } = useTranslation()
  40. const media = useBreakpoints()
  41. const isMobile = media === MediaType.mobile
  42. /*
  43. * app info
  44. */
  45. const [appUnavailable, setAppUnavailable] = useState<boolean>(false)
  46. const [isUnknwonReason, setIsUnknwonReason] = useState<boolean>(false)
  47. const [appId, setAppId] = useState<string>('')
  48. const [isPublicVersion, setIsPublicVersion] = useState<boolean>(true)
  49. const [siteInfo, setSiteInfo] = useState<SiteInfo | null>()
  50. const [promptConfig, setPromptConfig] = useState<PromptConfig | null>(null)
  51. const [inited, setInited] = useState<boolean>(false)
  52. const [plan, setPlan] = useState<string>('basic') // basic/plus/pro
  53. // Can Use metadata(https://beta.nextjs.org/docs/api-reference/metadata) to set title. But it only works in server side client.
  54. useEffect(() => {
  55. if (siteInfo?.title) {
  56. if (plan !== 'basic')
  57. document.title = `${siteInfo.title}`
  58. else
  59. document.title = `${siteInfo.title} - Powered by Dify`
  60. }
  61. }, [siteInfo?.title, plan])
  62. /*
  63. * conversation info
  64. */
  65. const [allConversationList, setAllConversationList] = useState<ConversationItem[]>([])
  66. const [isClearConversationList, { setTrue: clearConversationListTrue, setFalse: clearConversationListFalse }] = useBoolean(false)
  67. const [isClearPinnedConversationList, { setTrue: clearPinnedConversationListTrue, setFalse: clearPinnedConversationListFalse }] = useBoolean(false)
  68. const {
  69. conversationList,
  70. setConversationList,
  71. pinnedConversationList,
  72. setPinnedConversationList,
  73. currConversationId,
  74. setCurrConversationId,
  75. getConversationIdFromStorage,
  76. isNewConversation,
  77. currConversationInfo,
  78. currInputs,
  79. newConversationInputs,
  80. // existConversationInputs,
  81. resetNewConversationInputs,
  82. setCurrInputs,
  83. setNewConversationInfo,
  84. setExistConversationInfo,
  85. } = useConversation()
  86. const [hasMore, setHasMore] = useState<boolean>(true)
  87. const [hasPinnedMore, setHasPinnedMore] = useState<boolean>(true)
  88. const onMoreLoaded = ({ data: conversations, has_more }: any) => {
  89. setHasMore(has_more)
  90. if (isClearConversationList) {
  91. setConversationList(conversations)
  92. clearConversationListFalse()
  93. }
  94. else {
  95. setConversationList([...conversationList, ...conversations])
  96. }
  97. }
  98. const onPinnedMoreLoaded = ({ data: conversations, has_more }: any) => {
  99. setHasPinnedMore(has_more)
  100. if (isClearPinnedConversationList) {
  101. setPinnedConversationList(conversations)
  102. clearPinnedConversationListFalse()
  103. }
  104. else {
  105. setPinnedConversationList([...pinnedConversationList, ...conversations])
  106. }
  107. }
  108. const [controlUpdateConversationList, setControlUpdateConversationList] = useState(0)
  109. const noticeUpdateList = () => {
  110. setHasMore(true)
  111. clearConversationListTrue()
  112. setHasPinnedMore(true)
  113. clearPinnedConversationListTrue()
  114. setControlUpdateConversationList(Date.now())
  115. }
  116. const [suggestedQuestionsAfterAnswerConfig, setSuggestedQuestionsAfterAnswerConfig] = useState<SuggestedQuestionsAfterAnswerConfig | null>(null)
  117. const [speechToTextConfig, setSpeechToTextConfig] = useState<SuggestedQuestionsAfterAnswerConfig | null>(null)
  118. const [conversationIdChangeBecauseOfNew, setConversationIdChangeBecauseOfNew, getConversationIdChangeBecauseOfNew] = useGetState(false)
  119. const [isChatStarted, { setTrue: setChatStarted, setFalse: setChatNotStarted }] = useBoolean(false)
  120. const handleStartChat = (inputs: Record<string, any>) => {
  121. createNewChat()
  122. setConversationIdChangeBecauseOfNew(true)
  123. setCurrInputs(inputs)
  124. setChatStarted()
  125. // parse variables in introduction
  126. setChatList(generateNewChatListWithOpenstatement('', inputs))
  127. }
  128. const hasSetInputs = (() => {
  129. if (!isNewConversation)
  130. return true
  131. return isChatStarted
  132. })()
  133. // const conversationName = currConversationInfo?.name || t('share.chat.newChatDefaultName') as string
  134. const conversationIntroduction = currConversationInfo?.introduction || ''
  135. const handleConversationSwitch = () => {
  136. if (!inited)
  137. return
  138. if (!appId) {
  139. // wait for appId
  140. setTimeout(handleConversationSwitch, 100)
  141. return
  142. }
  143. // update inputs of current conversation
  144. let notSyncToStateIntroduction = ''
  145. let notSyncToStateInputs: Record<string, any> | undefined | null = {}
  146. if (!isNewConversation) {
  147. const item = allConversationList.find(item => item.id === currConversationId)
  148. notSyncToStateInputs = item?.inputs || {}
  149. setCurrInputs(notSyncToStateInputs)
  150. notSyncToStateIntroduction = item?.introduction || ''
  151. setExistConversationInfo({
  152. name: item?.name || '',
  153. introduction: notSyncToStateIntroduction,
  154. })
  155. }
  156. else {
  157. notSyncToStateInputs = newConversationInputs
  158. setCurrInputs(notSyncToStateInputs)
  159. }
  160. // update chat list of current conversation
  161. if (!isNewConversation && !conversationIdChangeBecauseOfNew && !isResponsing) {
  162. fetchChatList(currConversationId, isInstalledApp, installedAppInfo?.id).then((res: any) => {
  163. const { data } = res
  164. const newChatList: IChatItem[] = generateNewChatListWithOpenstatement(notSyncToStateIntroduction, notSyncToStateInputs)
  165. data.forEach((item: any) => {
  166. newChatList.push({
  167. id: `question-${item.id}`,
  168. content: item.query,
  169. isAnswer: false,
  170. })
  171. newChatList.push({
  172. id: item.id,
  173. content: item.answer,
  174. feedback: item.feedback,
  175. isAnswer: true,
  176. citation: item.retriever_resources,
  177. })
  178. })
  179. setChatList(newChatList)
  180. })
  181. }
  182. if (isNewConversation && isChatStarted)
  183. setChatList(generateNewChatListWithOpenstatement())
  184. setControlFocus(Date.now())
  185. }
  186. useEffect(handleConversationSwitch, [currConversationId, inited])
  187. /*
  188. * chat info. chat is under conversation.
  189. */
  190. const [chatList, setChatList, getChatList] = useGetState<IChatItem[]>([])
  191. const chatListDomRef = useRef<HTMLDivElement>(null)
  192. useEffect(() => {
  193. // scroll to bottom
  194. if (chatListDomRef.current)
  195. chatListDomRef.current.scrollTop = chatListDomRef.current.scrollHeight
  196. }, [chatList, currConversationId])
  197. // user can not edit inputs if user had send message
  198. const canEditInputs = !chatList.some(item => item.isAnswer === false) && isNewConversation
  199. const createNewChat = async () => {
  200. // if new chat is already exist, do not create new chat
  201. abortController?.abort()
  202. setResponsingFalse()
  203. if (conversationList.some(item => item.id === '-1'))
  204. return
  205. setConversationList(produce(conversationList, (draft) => {
  206. draft.unshift({
  207. id: '-1',
  208. name: t('share.chat.newChatDefaultName'),
  209. inputs: newConversationInputs,
  210. introduction: conversationIntroduction,
  211. })
  212. }))
  213. }
  214. // sometime introduction is not applied to state
  215. const generateNewChatListWithOpenstatement = (introduction?: string, inputs?: Record<string, any> | null) => {
  216. let caculatedIntroduction = introduction || conversationIntroduction || ''
  217. const caculatedPromptVariables = inputs || currInputs || null
  218. if (caculatedIntroduction && caculatedPromptVariables)
  219. caculatedIntroduction = replaceStringWithValues(caculatedIntroduction, promptConfig?.prompt_variables || [], caculatedPromptVariables)
  220. const openstatement = {
  221. id: `${Date.now()}`,
  222. content: caculatedIntroduction,
  223. isAnswer: true,
  224. feedbackDisabled: true,
  225. isOpeningStatement: isPublicVersion,
  226. }
  227. if (caculatedIntroduction)
  228. return [openstatement]
  229. return []
  230. }
  231. const fetchAllConversations = () => {
  232. return fetchConversations(isInstalledApp, installedAppInfo?.id, undefined, undefined, 100)
  233. }
  234. const fetchInitData = async () => {
  235. if (!isInstalledApp)
  236. await checkOrSetAccessToken()
  237. return Promise.all([isInstalledApp
  238. ? {
  239. app_id: installedAppInfo?.id,
  240. site: {
  241. title: installedAppInfo?.app.name,
  242. prompt_public: false,
  243. copyright: '',
  244. },
  245. plan: 'basic',
  246. }
  247. : fetchAppInfo(), fetchAllConversations(), fetchAppParams(isInstalledApp, installedAppInfo?.id)])
  248. }
  249. // init
  250. useEffect(() => {
  251. (async () => {
  252. try {
  253. const [appData, conversationData, appParams]: any = await fetchInitData()
  254. const { app_id: appId, site: siteInfo, plan }: any = appData
  255. setAppId(appId)
  256. setPlan(plan)
  257. const tempIsPublicVersion = siteInfo.prompt_public
  258. setIsPublicVersion(tempIsPublicVersion)
  259. const prompt_template = ''
  260. // handle current conversation id
  261. const { data: allConversations } = conversationData as { data: ConversationItem[]; has_more: boolean }
  262. const _conversationId = getConversationIdFromStorage(appId)
  263. const isNotNewConversation = allConversations.some(item => item.id === _conversationId)
  264. setAllConversationList(allConversations)
  265. // fetch new conversation info
  266. const { user_input_form, opening_statement: introduction, suggested_questions_after_answer, speech_to_text, retriever_resource }: any = appParams
  267. const prompt_variables = userInputsFormToPromptVariables(user_input_form)
  268. if (siteInfo.default_language)
  269. changeLanguage(siteInfo.default_language)
  270. setNewConversationInfo({
  271. name: t('share.chat.newChatDefaultName'),
  272. introduction,
  273. })
  274. setSiteInfo(siteInfo as SiteInfo)
  275. setPromptConfig({
  276. prompt_template,
  277. prompt_variables,
  278. } as PromptConfig)
  279. setSuggestedQuestionsAfterAnswerConfig(suggested_questions_after_answer)
  280. setSpeechToTextConfig(speech_to_text)
  281. // setConversationList(conversations as ConversationItem[])
  282. if (isNotNewConversation)
  283. setCurrConversationId(_conversationId, appId, false)
  284. setInited(true)
  285. }
  286. catch (e: any) {
  287. if (e.status === 404) {
  288. setAppUnavailable(true)
  289. }
  290. else {
  291. setIsUnknwonReason(true)
  292. setAppUnavailable(true)
  293. }
  294. }
  295. })()
  296. }, [])
  297. const [isResponsing, { setTrue: setResponsingTrue, setFalse: setResponsingFalse }] = useBoolean(false)
  298. const [abortController, setAbortController] = useState<AbortController | null>(null)
  299. const { notify } = useContext(ToastContext)
  300. const logError = (message: string) => {
  301. notify({ type: 'error', message })
  302. }
  303. const checkCanSend = () => {
  304. if (currConversationId !== '-1')
  305. return true
  306. const prompt_variables = promptConfig?.prompt_variables
  307. const inputs = currInputs
  308. if (!inputs || !prompt_variables || prompt_variables?.length === 0)
  309. return true
  310. let hasEmptyInput = ''
  311. const requiredVars = prompt_variables?.filter(({ key, name, required }) => {
  312. const res = (!key || !key.trim()) || (!name || !name.trim()) || (required || required === undefined || required === null)
  313. return res
  314. }) || [] // compatible with old version
  315. requiredVars.forEach(({ key, name }) => {
  316. if (hasEmptyInput)
  317. return
  318. if (!inputs?.[key])
  319. hasEmptyInput = name
  320. })
  321. if (hasEmptyInput) {
  322. logError(t('appDebug.errorMessage.valueOfVarRequired', { key: hasEmptyInput }))
  323. return false
  324. }
  325. return !hasEmptyInput
  326. }
  327. const [controlFocus, setControlFocus] = useState(0)
  328. const [isShowSuggestion, setIsShowSuggestion] = useState(false)
  329. const doShowSuggestion = isShowSuggestion && !isResponsing
  330. const [suggestQuestions, setSuggestQuestions] = useState<string[]>([])
  331. const [messageTaskId, setMessageTaskId] = useState('')
  332. const [hasStopResponded, setHasStopResponded, getHasStopResponded] = useGetState(false)
  333. const [shouldReload, setShouldReload] = useState(false)
  334. const handleSend = async (message: string) => {
  335. if (isResponsing) {
  336. notify({ type: 'info', message: t('appDebug.errorMessage.waitForResponse') })
  337. return
  338. }
  339. const data = {
  340. inputs: currInputs,
  341. query: message,
  342. conversation_id: isNewConversation ? null : currConversationId,
  343. }
  344. // qustion
  345. const questionId = `question-${Date.now()}`
  346. const questionItem = {
  347. id: questionId,
  348. content: message,
  349. isAnswer: false,
  350. }
  351. const placeholderAnswerId = `answer-placeholder-${Date.now()}`
  352. const placeholderAnswerItem = {
  353. id: placeholderAnswerId,
  354. content: '',
  355. isAnswer: true,
  356. }
  357. const newList = [...getChatList(), questionItem, placeholderAnswerItem]
  358. setChatList(newList)
  359. // answer
  360. const responseItem: IChatItem = {
  361. id: `${Date.now()}`,
  362. content: '',
  363. isAnswer: true,
  364. }
  365. let tempNewConversationId = ''
  366. setHasStopResponded(false)
  367. setResponsingTrue()
  368. setIsShowSuggestion(false)
  369. sendChatMessage(data, {
  370. getAbortController: (abortController) => {
  371. setAbortController(abortController)
  372. },
  373. onData: (message: string, isFirstMessage: boolean, { conversationId: newConversationId, messageId, taskId }: any) => {
  374. responseItem.content = responseItem.content + message
  375. responseItem.id = messageId
  376. if (isFirstMessage && newConversationId)
  377. tempNewConversationId = newConversationId
  378. setMessageTaskId(taskId)
  379. // closesure new list is outdated.
  380. const newListWithAnswer = produce(
  381. getChatList().filter(item => item.id !== responseItem.id && item.id !== placeholderAnswerId),
  382. (draft) => {
  383. if (!draft.find(item => item.id === questionId))
  384. draft.push({ ...questionItem })
  385. draft.push({ ...responseItem })
  386. })
  387. setChatList(newListWithAnswer)
  388. },
  389. async onCompleted(hasError?: boolean) {
  390. setResponsingFalse()
  391. if (hasError)
  392. return
  393. if (getConversationIdChangeBecauseOfNew()) {
  394. const { data: allConversations }: any = await fetchAllConversations()
  395. setAllConversationList(allConversations)
  396. noticeUpdateList()
  397. }
  398. setConversationIdChangeBecauseOfNew(false)
  399. resetNewConversationInputs()
  400. setChatNotStarted()
  401. setCurrConversationId(tempNewConversationId, appId, true)
  402. if (suggestedQuestionsAfterAnswerConfig?.enabled && !getHasStopResponded()) {
  403. const { data }: any = await fetchSuggestedQuestions(responseItem.id, isInstalledApp, installedAppInfo?.id)
  404. setSuggestQuestions(data)
  405. setIsShowSuggestion(true)
  406. }
  407. },
  408. onError(errorMessage, errorCode) {
  409. if (['provider_not_initialize', 'completion_request_error'].includes(errorCode as string))
  410. setShouldReload(true)
  411. setResponsingFalse()
  412. // role back placeholder answer
  413. setChatList(produce(getChatList(), (draft) => {
  414. draft.splice(draft.findIndex(item => item.id === placeholderAnswerId), 1)
  415. }))
  416. },
  417. }, isInstalledApp, installedAppInfo?.id)
  418. }
  419. const handleFeedback = async (messageId: string, feedback: Feedbacktype) => {
  420. await updateFeedback({ url: `/messages/${messageId}/feedbacks`, body: { rating: feedback.rating } }, isInstalledApp, installedAppInfo?.id)
  421. const newChatList = chatList.map((item) => {
  422. if (item.id === messageId) {
  423. return {
  424. ...item,
  425. feedback,
  426. }
  427. }
  428. return item
  429. })
  430. setChatList(newChatList)
  431. notify({ type: 'success', message: t('common.api.success') })
  432. }
  433. const handleReload = () => {
  434. setCurrConversationId('-1', appId, false)
  435. setChatNotStarted()
  436. setShouldReload(false)
  437. createNewChat()
  438. }
  439. const difyIcon = (
  440. <LogoHeader />
  441. )
  442. if (appUnavailable)
  443. return <AppUnavailable isUnknwonReason={isUnknwonReason} />
  444. if (!appId || !siteInfo || !promptConfig) {
  445. return <div className='flex h-screen w-full'>
  446. <Loading type='app' />
  447. </div>
  448. }
  449. return (
  450. <div>
  451. <Header
  452. title={siteInfo.title}
  453. icon=''
  454. customerIcon={difyIcon}
  455. icon_background={siteInfo.icon_background}
  456. isEmbedScene={true}
  457. isMobile={isMobile}
  458. />
  459. <div className={'flex bg-white overflow-hidden'}>
  460. <div className={cn(
  461. isInstalledApp ? s.installedApp : 'h-[calc(100vh_-_3rem)]',
  462. 'flex-grow flex flex-col overflow-y-auto',
  463. )
  464. }>
  465. <ConfigScene
  466. // conversationName={conversationName}
  467. hasSetInputs={hasSetInputs}
  468. isPublicVersion={isPublicVersion}
  469. siteInfo={siteInfo}
  470. promptConfig={promptConfig}
  471. onStartChat={handleStartChat}
  472. canEditInputs={canEditInputs}
  473. savedInputs={currInputs as Record<string, any>}
  474. onInputsChange={setCurrInputs}
  475. plan={plan}
  476. ></ConfigScene>
  477. {
  478. shouldReload && (
  479. <div className='flex items-center justify-between mb-5 px-4 py-2 bg-[#FEF0C7]'>
  480. <div className='flex items-center text-xs font-medium text-[#DC6803]'>
  481. <AlertTriangle className='mr-2 w-4 h-4' />
  482. {t('share.chat.temporarySystemIssue')}
  483. </div>
  484. <div
  485. className='flex items-center px-3 h-7 bg-white shadow-xs rounded-md text-xs font-medium text-gray-700 cursor-pointer'
  486. onClick={handleReload}
  487. >
  488. {t('share.chat.tryToSolve')}
  489. </div>
  490. </div>
  491. )
  492. }
  493. {
  494. hasSetInputs && (
  495. <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')}>
  496. <div className='h-full overflow-y-auto' ref={chatListDomRef}>
  497. <Chat
  498. chatList={chatList}
  499. onSend={handleSend}
  500. isHideFeedbackEdit
  501. onFeedback={handleFeedback}
  502. isResponsing={isResponsing}
  503. canStopResponsing={!!messageTaskId}
  504. abortResponsing={async () => {
  505. await stopChatMessageResponding(appId, messageTaskId, isInstalledApp, installedAppInfo?.id)
  506. setHasStopResponded(true)
  507. setResponsingFalse()
  508. }}
  509. checkCanSend={checkCanSend}
  510. controlFocus={controlFocus}
  511. isShowSuggestion={doShowSuggestion}
  512. suggestionList={suggestQuestions}
  513. displayScene='web'
  514. isShowSpeechToText={speechToTextConfig?.enabled}
  515. answerIcon={<LogoAvatar className='relative shrink-0' />}
  516. />
  517. </div>
  518. </div>)
  519. }
  520. {/* {isShowConfirm && (
  521. <Confirm
  522. title={t('share.chat.deleteConversation.title')}
  523. content={t('share.chat.deleteConversation.content')}
  524. isShow={isShowConfirm}
  525. onClose={hideConfirm}
  526. onConfirm={didDelete}
  527. onCancel={hideConfirm}
  528. />
  529. )} */}
  530. </div>
  531. </div>
  532. </div>
  533. )
  534. }
  535. export default React.memo(Main)