Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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. const allInputsHidden = useMemo(() => {
  218. return inputsForms.length > 0 && inputsForms.every(item => item.hide === true)
  219. }, [inputsForms])
  220. useEffect(() => {
  221. // init inputs from url params
  222. (async () => {
  223. const inputs = await getProcessedInputsFromUrlParams()
  224. setInitInputs(inputs)
  225. })()
  226. }, [])
  227. useEffect(() => {
  228. const conversationInputs: Record<string, any> = {}
  229. inputsForms.forEach((item: any) => {
  230. conversationInputs[item.variable] = item.default || null
  231. })
  232. handleNewConversationInputsChange(conversationInputs)
  233. }, [handleNewConversationInputsChange, inputsForms])
  234. const { data: newConversation } = useSWR(newConversationId ? [isInstalledApp, appId, newConversationId] : null, () => generationConversationName(isInstalledApp, appId, newConversationId), { revalidateOnFocus: false })
  235. const [originConversationList, setOriginConversationList] = useState<ConversationItem[]>([])
  236. useEffect(() => {
  237. if (appConversationData?.data && !appConversationDataLoading)
  238. setOriginConversationList(appConversationData?.data)
  239. }, [appConversationData, appConversationDataLoading])
  240. const conversationList = useMemo(() => {
  241. const data = originConversationList.slice()
  242. if (showNewConversationItemInList && data[0]?.id !== '') {
  243. data.unshift({
  244. id: '',
  245. name: t('share.chat.newChatDefaultName'),
  246. inputs: {},
  247. introduction: '',
  248. })
  249. }
  250. return data
  251. }, [originConversationList, showNewConversationItemInList, t])
  252. useEffect(() => {
  253. if (newConversation) {
  254. setOriginConversationList(produce((draft) => {
  255. const index = draft.findIndex(item => item.id === newConversation.id)
  256. if (index > -1)
  257. draft[index] = newConversation
  258. else
  259. draft.unshift(newConversation)
  260. }))
  261. }
  262. }, [newConversation])
  263. const currentConversationItem = useMemo(() => {
  264. let conversationItem = conversationList.find(item => item.id === currentConversationId)
  265. if (!conversationItem && pinnedConversationList.length)
  266. conversationItem = pinnedConversationList.find(item => item.id === currentConversationId)
  267. return conversationItem
  268. }, [conversationList, currentConversationId, pinnedConversationList])
  269. const currentConversationLatestInputs = useMemo(() => {
  270. if (!currentConversationId || !appChatListData?.data.length)
  271. return newConversationInputsRef.current || {}
  272. return appChatListData.data.slice().pop().inputs || {}
  273. }, [appChatListData, currentConversationId])
  274. const [currentConversationInputs, setCurrentConversationInputs] = useState<Record<string, any>>(currentConversationLatestInputs || {})
  275. useEffect(() => {
  276. if (currentConversationItem)
  277. setCurrentConversationInputs(currentConversationLatestInputs || {})
  278. }, [currentConversationItem, currentConversationLatestInputs])
  279. const { notify } = useToastContext()
  280. const checkInputsRequired = useCallback((silent?: boolean) => {
  281. if (allInputsHidden)
  282. return true
  283. let hasEmptyInput = ''
  284. let fileIsUploading = false
  285. const requiredVars = inputsForms.filter(({ required }) => required)
  286. if (requiredVars.length) {
  287. requiredVars.forEach(({ variable, label, type }) => {
  288. if (hasEmptyInput)
  289. return
  290. if (fileIsUploading)
  291. return
  292. if (!newConversationInputsRef.current[variable] && !silent)
  293. hasEmptyInput = label as string
  294. if ((type === InputVarType.singleFile || type === InputVarType.multiFiles) && newConversationInputsRef.current[variable] && !silent) {
  295. const files = newConversationInputsRef.current[variable]
  296. if (Array.isArray(files))
  297. fileIsUploading = files.find(item => item.transferMethod === TransferMethod.local_file && !item.uploadedId)
  298. else
  299. fileIsUploading = files.transferMethod === TransferMethod.local_file && !files.uploadedId
  300. }
  301. })
  302. }
  303. if (hasEmptyInput) {
  304. notify({ type: 'error', message: t('appDebug.errorMessage.valueOfVarRequired', { key: hasEmptyInput }) })
  305. return false
  306. }
  307. if (fileIsUploading) {
  308. notify({ type: 'info', message: t('appDebug.errorMessage.waitForFileUpload') })
  309. return
  310. }
  311. return true
  312. }, [inputsForms, notify, t, allInputsHidden])
  313. const handleStartChat = useCallback((callback?: any) => {
  314. if (checkInputsRequired()) {
  315. setShowNewConversationItemInList(true)
  316. callback?.()
  317. }
  318. }, [setShowNewConversationItemInList, checkInputsRequired])
  319. const currentChatInstanceRef = useRef<{ handleStop: () => void }>({ handleStop: noop })
  320. const handleChangeConversation = useCallback((conversationId: string) => {
  321. currentChatInstanceRef.current.handleStop()
  322. setNewConversationId('')
  323. handleConversationIdInfoChange(conversationId)
  324. if (conversationId)
  325. setClearChatList(false)
  326. }, [handleConversationIdInfoChange, setClearChatList])
  327. const handleNewConversation = useCallback(async () => {
  328. currentChatInstanceRef.current.handleStop()
  329. setShowNewConversationItemInList(true)
  330. handleChangeConversation('')
  331. handleNewConversationInputsChange(await getProcessedInputsFromUrlParams())
  332. setClearChatList(true)
  333. }, [handleChangeConversation, setShowNewConversationItemInList, handleNewConversationInputsChange, setClearChatList])
  334. const handleNewConversationCompleted = useCallback((newConversationId: string) => {
  335. setNewConversationId(newConversationId)
  336. handleConversationIdInfoChange(newConversationId)
  337. setShowNewConversationItemInList(false)
  338. mutateAppConversationData()
  339. }, [mutateAppConversationData, handleConversationIdInfoChange])
  340. const handleFeedback = useCallback(async (messageId: string, feedback: Feedback) => {
  341. await updateFeedback({ url: `/messages/${messageId}/feedbacks`, body: { rating: feedback.rating } }, isInstalledApp, appId)
  342. notify({ type: 'success', message: t('common.api.success') })
  343. }, [isInstalledApp, appId, t, notify])
  344. return {
  345. appInfoError,
  346. appInfoLoading: appInfoLoading || (systemFeatures.webapp_auth.enabled && (isGettingAccessMode || isCheckingPermission)),
  347. accessMode: systemFeatures.webapp_auth.enabled ? appAccessMode?.accessMode : AccessMode.PUBLIC,
  348. userCanAccess: systemFeatures.webapp_auth.enabled ? userCanAccessResult?.result : true,
  349. isInstalledApp,
  350. allowResetChat,
  351. appId,
  352. currentConversationId,
  353. currentConversationItem,
  354. handleConversationIdInfoChange,
  355. appData,
  356. appParams: appParams || {} as ChatConfig,
  357. appMeta,
  358. appPinnedConversationData,
  359. appConversationData,
  360. appConversationDataLoading,
  361. appChatListData,
  362. appChatListDataLoading,
  363. appPrevChatList,
  364. pinnedConversationList,
  365. conversationList,
  366. setShowNewConversationItemInList,
  367. newConversationInputs,
  368. newConversationInputsRef,
  369. handleNewConversationInputsChange,
  370. inputsForms,
  371. handleNewConversation,
  372. handleStartChat,
  373. handleChangeConversation,
  374. handleNewConversationCompleted,
  375. newConversationId,
  376. chatShouldReloadKey,
  377. handleFeedback,
  378. currentChatInstanceRef,
  379. clearChatList,
  380. setClearChatList,
  381. isResponding,
  382. setIsResponding,
  383. currentConversationInputs,
  384. setCurrentConversationInputs,
  385. allInputsHidden,
  386. }
  387. }