You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. import {
  2. useCallback,
  3. useEffect,
  4. useMemo,
  5. useRef,
  6. useState,
  7. } from 'react'
  8. import { useTranslation } from 'react-i18next'
  9. import useSWR from 'swr'
  10. import { useLocalStorageState } from 'ahooks'
  11. import produce from 'immer'
  12. import type {
  13. ChatConfig,
  14. ChatItem,
  15. Feedback,
  16. } from '../types'
  17. import { CONVERSATION_ID_INFO } from '../constants'
  18. import { buildChatItemTree, getProcessedInputsFromUrlParams, getProcessedSystemVariablesFromUrlParams } from '../utils'
  19. import { getProcessedFilesFromResponse } from '../../file-uploader/utils'
  20. import {
  21. fetchAppInfo,
  22. fetchAppMeta,
  23. fetchAppParams,
  24. fetchChatList,
  25. fetchConversations,
  26. generationConversationName,
  27. updateFeedback,
  28. } from '@/service/share'
  29. import type {
  30. // AppData,
  31. ConversationItem,
  32. } from '@/models/share'
  33. import { useToastContext } from '@/app/components/base/toast'
  34. import { changeLanguage } from '@/i18n/i18next-config'
  35. import { InputVarType } from '@/app/components/workflow/types'
  36. import { TransferMethod } from '@/types/app'
  37. import { addFileInfos, sortAgentSorts } from '@/app/components/tools/utils'
  38. import { noop } from 'lodash-es'
  39. import { useGetAppAccessMode, useGetUserCanAccessApp } from '@/service/access-control'
  40. import { useGlobalPublicStore } from '@/context/global-public-context'
  41. import { AccessMode } from '@/models/access-control'
  42. function getFormattedChatList(messages: any[]) {
  43. const newChatList: ChatItem[] = []
  44. messages.forEach((item) => {
  45. const questionFiles = item.message_files?.filter((file: any) => file.belongs_to === 'user') || []
  46. newChatList.push({
  47. id: `question-${item.id}`,
  48. content: item.query,
  49. isAnswer: false,
  50. message_files: getProcessedFilesFromResponse(questionFiles.map((item: any) => ({ ...item, related_id: item.id }))),
  51. parentMessageId: item.parent_message_id || undefined,
  52. })
  53. const answerFiles = item.message_files?.filter((file: any) => file.belongs_to === 'assistant') || []
  54. newChatList.push({
  55. id: item.id,
  56. content: item.answer,
  57. agent_thoughts: addFileInfos(item.agent_thoughts ? sortAgentSorts(item.agent_thoughts) : item.agent_thoughts, item.message_files),
  58. feedback: item.feedback,
  59. isAnswer: true,
  60. citation: item.retriever_resources,
  61. message_files: getProcessedFilesFromResponse(answerFiles.map((item: any) => ({ ...item, related_id: item.id }))),
  62. parentMessageId: `question-${item.id}`,
  63. })
  64. })
  65. return newChatList
  66. }
  67. export const useEmbeddedChatbot = () => {
  68. const isInstalledApp = false
  69. const systemFeatures = useGlobalPublicStore(s => s.systemFeatures)
  70. const { data: appInfo, isLoading: appInfoLoading, error: appInfoError } = useSWR('appInfo', fetchAppInfo)
  71. const { isPending: isGettingAccessMode, data: appAccessMode } = useGetAppAccessMode({
  72. appId: appInfo?.app_id,
  73. isInstalledApp,
  74. enabled: systemFeatures.webapp_auth.enabled,
  75. })
  76. const { isPending: isCheckingPermission, data: userCanAccessResult } = useGetUserCanAccessApp({
  77. appId: appInfo?.app_id,
  78. isInstalledApp,
  79. enabled: systemFeatures.webapp_auth.enabled,
  80. })
  81. const appData = useMemo(() => {
  82. return appInfo
  83. }, [appInfo])
  84. const appId = useMemo(() => appData?.app_id, [appData])
  85. const [userId, setUserId] = useState<string>()
  86. const [conversationId, setConversationId] = useState<string>()
  87. useEffect(() => {
  88. getProcessedSystemVariablesFromUrlParams().then(({ user_id, conversation_id }) => {
  89. setUserId(user_id)
  90. setConversationId(conversation_id)
  91. })
  92. }, [])
  93. useEffect(() => {
  94. const setLanguageFromParams = async () => {
  95. // Check URL parameters for language override
  96. const urlParams = new URLSearchParams(window.location.search)
  97. const localeParam = urlParams.get('locale')
  98. // Check for encoded system variables
  99. const systemVariables = await getProcessedSystemVariablesFromUrlParams()
  100. const localeFromSysVar = systemVariables.locale
  101. if (localeParam) {
  102. // If locale parameter exists in URL, use it instead of default
  103. changeLanguage(localeParam)
  104. }
  105. else if (localeFromSysVar) {
  106. // If locale is set as a system variable, use that
  107. changeLanguage(localeFromSysVar)
  108. }
  109. else if (appInfo?.site.default_language) {
  110. // Otherwise use the default from app config
  111. changeLanguage(appInfo.site.default_language)
  112. }
  113. }
  114. setLanguageFromParams()
  115. }, [appInfo])
  116. const [conversationIdInfo, setConversationIdInfo] = useLocalStorageState<Record<string, Record<string, string>>>(CONVERSATION_ID_INFO, {
  117. defaultValue: {},
  118. })
  119. const allowResetChat = !conversationId
  120. const currentConversationId = useMemo(() => conversationIdInfo?.[appId || '']?.[userId || 'DEFAULT'] || conversationId || '',
  121. [appId, conversationIdInfo, userId, conversationId])
  122. const handleConversationIdInfoChange = useCallback((changeConversationId: string) => {
  123. if (appId) {
  124. let prevValue = conversationIdInfo?.[appId || '']
  125. if (typeof prevValue === 'string')
  126. prevValue = {}
  127. setConversationIdInfo({
  128. ...conversationIdInfo,
  129. [appId || '']: {
  130. ...prevValue,
  131. [userId || 'DEFAULT']: changeConversationId,
  132. },
  133. })
  134. }
  135. }, [appId, conversationIdInfo, setConversationIdInfo, userId])
  136. const [newConversationId, setNewConversationId] = useState('')
  137. const chatShouldReloadKey = useMemo(() => {
  138. if (currentConversationId === newConversationId)
  139. return ''
  140. return currentConversationId
  141. }, [currentConversationId, newConversationId])
  142. const { data: appParams } = useSWR(['appParams', isInstalledApp, appId], () => fetchAppParams(isInstalledApp, appId))
  143. const { data: appMeta } = useSWR(['appMeta', isInstalledApp, appId], () => fetchAppMeta(isInstalledApp, appId))
  144. const { data: appPinnedConversationData } = useSWR(['appConversationData', isInstalledApp, appId, true], () => fetchConversations(isInstalledApp, appId, undefined, true, 100))
  145. const { data: appConversationData, isLoading: appConversationDataLoading, mutate: mutateAppConversationData } = useSWR(['appConversationData', isInstalledApp, appId, false], () => fetchConversations(isInstalledApp, appId, undefined, false, 100))
  146. const { data: appChatListData, isLoading: appChatListDataLoading } = useSWR(chatShouldReloadKey ? ['appChatList', chatShouldReloadKey, isInstalledApp, appId] : null, () => fetchChatList(chatShouldReloadKey, isInstalledApp, appId))
  147. const [clearChatList, setClearChatList] = useState(false)
  148. const [isResponding, setIsResponding] = useState(false)
  149. const appPrevChatList = useMemo(
  150. () => (currentConversationId && appChatListData?.data.length)
  151. ? buildChatItemTree(getFormattedChatList(appChatListData.data))
  152. : [],
  153. [appChatListData, currentConversationId],
  154. )
  155. const [showNewConversationItemInList, setShowNewConversationItemInList] = useState(false)
  156. const pinnedConversationList = useMemo(() => {
  157. return appPinnedConversationData?.data || []
  158. }, [appPinnedConversationData])
  159. const { t } = useTranslation()
  160. const newConversationInputsRef = useRef<Record<string, any>>({})
  161. const [newConversationInputs, setNewConversationInputs] = useState<Record<string, any>>({})
  162. const [initInputs, setInitInputs] = useState<Record<string, any>>({})
  163. const handleNewConversationInputsChange = useCallback((newInputs: Record<string, any>) => {
  164. newConversationInputsRef.current = newInputs
  165. setNewConversationInputs(newInputs)
  166. }, [])
  167. const inputsForms = useMemo(() => {
  168. return (appParams?.user_input_form || []).filter((item: any) => !item.external_data_tool).map((item: any) => {
  169. if (item.paragraph) {
  170. let value = initInputs[item.paragraph.variable]
  171. if (value && item.paragraph.max_length && value.length > item.paragraph.max_length)
  172. value = value.slice(0, item.paragraph.max_length)
  173. return {
  174. ...item.paragraph,
  175. default: value || item.default,
  176. type: 'paragraph',
  177. }
  178. }
  179. if (item.number) {
  180. const convertedNumber = Number(initInputs[item.number.variable]) ?? undefined
  181. return {
  182. ...item.number,
  183. default: convertedNumber || item.default,
  184. type: 'number',
  185. }
  186. }
  187. if (item.select) {
  188. const isInputInOptions = item.select.options.includes(initInputs[item.select.variable])
  189. return {
  190. ...item.select,
  191. default: (isInputInOptions ? initInputs[item.select.variable] : undefined) || item.default,
  192. type: 'select',
  193. }
  194. }
  195. if (item['file-list']) {
  196. return {
  197. ...item['file-list'],
  198. type: 'file-list',
  199. }
  200. }
  201. if (item.file) {
  202. return {
  203. ...item.file,
  204. type: 'file',
  205. }
  206. }
  207. let value = initInputs[item['text-input'].variable]
  208. if (value && item['text-input'].max_length && value.length > item['text-input'].max_length)
  209. value = value.slice(0, item['text-input'].max_length)
  210. return {
  211. ...item['text-input'],
  212. default: value || item.default,
  213. type: 'text-input',
  214. }
  215. })
  216. }, [initInputs, appParams])
  217. useEffect(() => {
  218. // init inputs from url params
  219. (async () => {
  220. const inputs = await getProcessedInputsFromUrlParams()
  221. setInitInputs(inputs)
  222. })()
  223. }, [])
  224. useEffect(() => {
  225. const conversationInputs: Record<string, any> = {}
  226. inputsForms.forEach((item: any) => {
  227. conversationInputs[item.variable] = item.default || null
  228. })
  229. handleNewConversationInputsChange(conversationInputs)
  230. }, [handleNewConversationInputsChange, inputsForms])
  231. const { data: newConversation } = useSWR(newConversationId ? [isInstalledApp, appId, newConversationId] : null, () => generationConversationName(isInstalledApp, appId, newConversationId), { revalidateOnFocus: false })
  232. const [originConversationList, setOriginConversationList] = useState<ConversationItem[]>([])
  233. useEffect(() => {
  234. if (appConversationData?.data && !appConversationDataLoading)
  235. setOriginConversationList(appConversationData?.data)
  236. }, [appConversationData, appConversationDataLoading])
  237. const conversationList = useMemo(() => {
  238. const data = originConversationList.slice()
  239. if (showNewConversationItemInList && data[0]?.id !== '') {
  240. data.unshift({
  241. id: '',
  242. name: t('share.chat.newChatDefaultName'),
  243. inputs: {},
  244. introduction: '',
  245. })
  246. }
  247. return data
  248. }, [originConversationList, showNewConversationItemInList, t])
  249. useEffect(() => {
  250. if (newConversation) {
  251. setOriginConversationList(produce((draft) => {
  252. const index = draft.findIndex(item => item.id === newConversation.id)
  253. if (index > -1)
  254. draft[index] = newConversation
  255. else
  256. draft.unshift(newConversation)
  257. }))
  258. }
  259. }, [newConversation])
  260. const currentConversationItem = useMemo(() => {
  261. let conversationItem = conversationList.find(item => item.id === currentConversationId)
  262. if (!conversationItem && pinnedConversationList.length)
  263. conversationItem = pinnedConversationList.find(item => item.id === currentConversationId)
  264. return conversationItem
  265. }, [conversationList, currentConversationId, pinnedConversationList])
  266. const currentConversationLatestInputs = useMemo(() => {
  267. if (!currentConversationId || !appChatListData?.data.length)
  268. return newConversationInputsRef.current || {}
  269. return appChatListData.data.slice().pop().inputs || {}
  270. }, [appChatListData, currentConversationId])
  271. const [currentConversationInputs, setCurrentConversationInputs] = useState<Record<string, any>>(currentConversationLatestInputs || {})
  272. useEffect(() => {
  273. if (currentConversationItem)
  274. setCurrentConversationInputs(currentConversationLatestInputs || {})
  275. }, [currentConversationItem, currentConversationLatestInputs])
  276. const { notify } = useToastContext()
  277. const checkInputsRequired = useCallback((silent?: boolean) => {
  278. let hasEmptyInput = ''
  279. let fileIsUploading = false
  280. const requiredVars = inputsForms.filter(({ required }) => required)
  281. if (requiredVars.length) {
  282. requiredVars.forEach(({ variable, label, type }) => {
  283. if (hasEmptyInput)
  284. return
  285. if (fileIsUploading)
  286. return
  287. if (!newConversationInputsRef.current[variable] && !silent)
  288. hasEmptyInput = label as string
  289. if ((type === InputVarType.singleFile || type === InputVarType.multiFiles) && newConversationInputsRef.current[variable] && !silent) {
  290. const files = newConversationInputsRef.current[variable]
  291. if (Array.isArray(files))
  292. fileIsUploading = files.find(item => item.transferMethod === TransferMethod.local_file && !item.uploadedId)
  293. else
  294. fileIsUploading = files.transferMethod === TransferMethod.local_file && !files.uploadedId
  295. }
  296. })
  297. }
  298. if (hasEmptyInput) {
  299. notify({ type: 'error', message: t('appDebug.errorMessage.valueOfVarRequired', { key: hasEmptyInput }) })
  300. return false
  301. }
  302. if (fileIsUploading) {
  303. notify({ type: 'info', message: t('appDebug.errorMessage.waitForFileUpload') })
  304. return
  305. }
  306. return true
  307. }, [inputsForms, notify, t])
  308. const handleStartChat = useCallback((callback?: any) => {
  309. if (checkInputsRequired()) {
  310. setShowNewConversationItemInList(true)
  311. callback?.()
  312. }
  313. }, [setShowNewConversationItemInList, checkInputsRequired])
  314. const currentChatInstanceRef = useRef<{ handleStop: () => void }>({ handleStop: noop })
  315. const handleChangeConversation = useCallback((conversationId: string) => {
  316. currentChatInstanceRef.current.handleStop()
  317. setNewConversationId('')
  318. handleConversationIdInfoChange(conversationId)
  319. if (conversationId)
  320. setClearChatList(false)
  321. }, [handleConversationIdInfoChange, setClearChatList])
  322. const handleNewConversation = useCallback(async () => {
  323. currentChatInstanceRef.current.handleStop()
  324. setShowNewConversationItemInList(true)
  325. handleChangeConversation('')
  326. handleNewConversationInputsChange(await getProcessedInputsFromUrlParams())
  327. setClearChatList(true)
  328. }, [handleChangeConversation, setShowNewConversationItemInList, handleNewConversationInputsChange, setClearChatList])
  329. const handleNewConversationCompleted = useCallback((newConversationId: string) => {
  330. setNewConversationId(newConversationId)
  331. handleConversationIdInfoChange(newConversationId)
  332. setShowNewConversationItemInList(false)
  333. mutateAppConversationData()
  334. }, [mutateAppConversationData, handleConversationIdInfoChange])
  335. const handleFeedback = useCallback(async (messageId: string, feedback: Feedback) => {
  336. await updateFeedback({ url: `/messages/${messageId}/feedbacks`, body: { rating: feedback.rating } }, isInstalledApp, appId)
  337. notify({ type: 'success', message: t('common.api.success') })
  338. }, [isInstalledApp, appId, t, notify])
  339. return {
  340. appInfoError,
  341. appInfoLoading: appInfoLoading || (systemFeatures.webapp_auth.enabled && (isGettingAccessMode || isCheckingPermission)),
  342. accessMode: systemFeatures.webapp_auth.enabled ? appAccessMode?.accessMode : AccessMode.PUBLIC,
  343. userCanAccess: systemFeatures.webapp_auth.enabled ? userCanAccessResult?.result : true,
  344. isInstalledApp,
  345. allowResetChat,
  346. appId,
  347. currentConversationId,
  348. currentConversationItem,
  349. handleConversationIdInfoChange,
  350. appData,
  351. appParams: appParams || {} as ChatConfig,
  352. appMeta,
  353. appPinnedConversationData,
  354. appConversationData,
  355. appConversationDataLoading,
  356. appChatListData,
  357. appChatListDataLoading,
  358. appPrevChatList,
  359. pinnedConversationList,
  360. conversationList,
  361. setShowNewConversationItemInList,
  362. newConversationInputs,
  363. newConversationInputsRef,
  364. handleNewConversationInputsChange,
  365. inputsForms,
  366. handleNewConversation,
  367. handleStartChat,
  368. handleChangeConversation,
  369. handleNewConversationCompleted,
  370. newConversationId,
  371. chatShouldReloadKey,
  372. handleFeedback,
  373. currentChatInstanceRef,
  374. clearChatList,
  375. setClearChatList,
  376. isResponding,
  377. setIsResponding,
  378. currentConversationInputs,
  379. setCurrentConversationInputs,
  380. }
  381. }