index.tsx 20 KB

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