Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

hooks.tsx 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  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. Callback,
  14. ChatConfig,
  15. ChatItem,
  16. Feedback,
  17. } from '../types'
  18. import { CONVERSATION_ID_INFO } from '../constants'
  19. import { buildChatItemTree, getProcessedSystemVariablesFromUrlParams } from '../utils'
  20. import { addFileInfos, sortAgentSorts } from '../../../tools/utils'
  21. import { getProcessedFilesFromResponse } from '@/app/components/base/file-uploader/utils'
  22. import {
  23. delConversation,
  24. fetchAppInfo,
  25. fetchAppMeta,
  26. fetchAppParams,
  27. fetchChatList,
  28. fetchConversations,
  29. generationConversationName,
  30. pinConversation,
  31. renameConversation,
  32. unpinConversation,
  33. updateFeedback,
  34. } from '@/service/share'
  35. import type { InstalledApp } from '@/models/explore'
  36. import type {
  37. AppData,
  38. ConversationItem,
  39. } from '@/models/share'
  40. import { useToastContext } from '@/app/components/base/toast'
  41. import { changeLanguage } from '@/i18n/i18next-config'
  42. import { useAppFavicon } from '@/hooks/use-app-favicon'
  43. import { InputVarType } from '@/app/components/workflow/types'
  44. import { TransferMethod } from '@/types/app'
  45. import { noop } from 'lodash-es'
  46. import { useGetAppAccessMode, useGetUserCanAccessApp } from '@/service/access-control'
  47. import { useGlobalPublicStore } from '@/context/global-public-context'
  48. import { AccessMode } from '@/models/access-control'
  49. function getFormattedChatList(messages: any[]) {
  50. const newChatList: ChatItem[] = []
  51. messages.forEach((item) => {
  52. const questionFiles = item.message_files?.filter((file: any) => file.belongs_to === 'user') || []
  53. newChatList.push({
  54. id: `question-${item.id}`,
  55. content: item.query,
  56. isAnswer: false,
  57. message_files: getProcessedFilesFromResponse(questionFiles.map((item: any) => ({ ...item, related_id: item.id, upload_file_id: item.upload_file_id }))),
  58. parentMessageId: item.parent_message_id || undefined,
  59. })
  60. const answerFiles = item.message_files?.filter((file: any) => file.belongs_to === 'assistant') || []
  61. newChatList.push({
  62. id: item.id,
  63. content: item.answer,
  64. agent_thoughts: addFileInfos(item.agent_thoughts ? sortAgentSorts(item.agent_thoughts) : item.agent_thoughts, item.message_files),
  65. feedback: item.feedback,
  66. isAnswer: true,
  67. citation: item.retriever_resources,
  68. message_files: getProcessedFilesFromResponse(answerFiles.map((item: any) => ({ ...item, related_id: item.id, upload_file_id: item.upload_file_id }))),
  69. parentMessageId: `question-${item.id}`,
  70. })
  71. })
  72. return newChatList
  73. }
  74. export const useChatWithHistory = (installedAppInfo?: InstalledApp) => {
  75. const isInstalledApp = useMemo(() => !!installedAppInfo, [installedAppInfo])
  76. const systemFeatures = useGlobalPublicStore(s => s.systemFeatures)
  77. const { data: appInfo, isLoading: appInfoLoading, error: appInfoError } = useSWR(installedAppInfo ? null : 'appInfo', fetchAppInfo)
  78. const { isPending: isGettingAccessMode, data: appAccessMode } = useGetAppAccessMode({
  79. appId: installedAppInfo?.app.id || appInfo?.app_id,
  80. isInstalledApp,
  81. enabled: systemFeatures.webapp_auth.enabled,
  82. })
  83. const { isPending: isCheckingPermission, data: userCanAccessResult } = useGetUserCanAccessApp({
  84. appId: installedAppInfo?.app.id || appInfo?.app_id,
  85. isInstalledApp,
  86. enabled: systemFeatures.webapp_auth.enabled,
  87. })
  88. useAppFavicon({
  89. enable: !installedAppInfo,
  90. icon_type: appInfo?.site.icon_type,
  91. icon: appInfo?.site.icon,
  92. icon_background: appInfo?.site.icon_background,
  93. icon_url: appInfo?.site.icon_url,
  94. })
  95. const appData = useMemo(() => {
  96. if (isInstalledApp) {
  97. const { id, app } = installedAppInfo!
  98. return {
  99. app_id: id,
  100. site: {
  101. title: app.name,
  102. icon_type: app.icon_type,
  103. icon: app.icon,
  104. icon_background: app.icon_background,
  105. icon_url: app.icon_url,
  106. prompt_public: false,
  107. copyright: '',
  108. show_workflow_steps: true,
  109. use_icon_as_answer_icon: app.use_icon_as_answer_icon,
  110. },
  111. plan: 'basic',
  112. } as AppData
  113. }
  114. return appInfo
  115. }, [isInstalledApp, installedAppInfo, appInfo])
  116. const appId = useMemo(() => appData?.app_id, [appData])
  117. const [userId, setUserId] = useState<string>()
  118. useEffect(() => {
  119. getProcessedSystemVariablesFromUrlParams().then(({ user_id }) => {
  120. setUserId(user_id)
  121. })
  122. }, [])
  123. useEffect(() => {
  124. if (appData?.site.default_language)
  125. changeLanguage(appData.site.default_language)
  126. }, [appData])
  127. const [sidebarCollapseState, setSidebarCollapseState] = useState<boolean>(false)
  128. const handleSidebarCollapse = useCallback((state: boolean) => {
  129. if (appId) {
  130. setSidebarCollapseState(state)
  131. localStorage.setItem('webappSidebarCollapse', state ? 'collapsed' : 'expanded')
  132. }
  133. }, [appId, setSidebarCollapseState])
  134. useEffect(() => {
  135. if (appId) {
  136. const localState = localStorage.getItem('webappSidebarCollapse')
  137. setSidebarCollapseState(localState === 'collapsed')
  138. }
  139. }, [appId])
  140. const [conversationIdInfo, setConversationIdInfo] = useLocalStorageState<Record<string, Record<string, string>>>(CONVERSATION_ID_INFO, {
  141. defaultValue: {},
  142. })
  143. const currentConversationId = useMemo(() => conversationIdInfo?.[appId || '']?.[userId || 'DEFAULT'] || '', [appId, conversationIdInfo, userId])
  144. const handleConversationIdInfoChange = useCallback((changeConversationId: string) => {
  145. if (appId) {
  146. let prevValue = conversationIdInfo?.[appId || '']
  147. if (typeof prevValue === 'string')
  148. prevValue = {}
  149. setConversationIdInfo({
  150. ...conversationIdInfo,
  151. [appId || '']: {
  152. ...prevValue,
  153. [userId || 'DEFAULT']: changeConversationId,
  154. },
  155. })
  156. }
  157. }, [appId, conversationIdInfo, setConversationIdInfo, userId])
  158. const [newConversationId, setNewConversationId] = useState('')
  159. const chatShouldReloadKey = useMemo(() => {
  160. if (currentConversationId === newConversationId)
  161. return ''
  162. return currentConversationId
  163. }, [currentConversationId, newConversationId])
  164. const { data: appParams } = useSWR(['appParams', isInstalledApp, appId], () => fetchAppParams(isInstalledApp, appId))
  165. const { data: appMeta } = useSWR(['appMeta', isInstalledApp, appId], () => fetchAppMeta(isInstalledApp, appId))
  166. const { data: appPinnedConversationData, mutate: mutateAppPinnedConversationData } = useSWR(['appConversationData', isInstalledApp, appId, true], () => fetchConversations(isInstalledApp, appId, undefined, true, 100))
  167. const { data: appConversationData, isLoading: appConversationDataLoading, mutate: mutateAppConversationData } = useSWR(['appConversationData', isInstalledApp, appId, false], () => fetchConversations(isInstalledApp, appId, undefined, false, 100))
  168. const { data: appChatListData, isLoading: appChatListDataLoading } = useSWR(chatShouldReloadKey ? ['appChatList', chatShouldReloadKey, isInstalledApp, appId] : null, () => fetchChatList(chatShouldReloadKey, isInstalledApp, appId))
  169. const [clearChatList, setClearChatList] = useState(false)
  170. const [isResponding, setIsResponding] = useState(false)
  171. const appPrevChatTree = useMemo(
  172. () => (currentConversationId && appChatListData?.data.length)
  173. ? buildChatItemTree(getFormattedChatList(appChatListData.data))
  174. : [],
  175. [appChatListData, currentConversationId],
  176. )
  177. const [showNewConversationItemInList, setShowNewConversationItemInList] = useState(false)
  178. const pinnedConversationList = useMemo(() => {
  179. return appPinnedConversationData?.data || []
  180. }, [appPinnedConversationData])
  181. const { t } = useTranslation()
  182. const newConversationInputsRef = useRef<Record<string, any>>({})
  183. const [newConversationInputs, setNewConversationInputs] = useState<Record<string, any>>({})
  184. const handleNewConversationInputsChange = useCallback((newInputs: Record<string, any>) => {
  185. newConversationInputsRef.current = newInputs
  186. setNewConversationInputs(newInputs)
  187. }, [])
  188. const inputsForms = useMemo(() => {
  189. return (appParams?.user_input_form || []).filter((item: any) => !item.external_data_tool).map((item: any) => {
  190. if (item.paragraph) {
  191. return {
  192. ...item.paragraph,
  193. type: 'paragraph',
  194. }
  195. }
  196. if (item.number) {
  197. return {
  198. ...item.number,
  199. type: 'number',
  200. }
  201. }
  202. if (item.select) {
  203. return {
  204. ...item.select,
  205. type: 'select',
  206. }
  207. }
  208. if (item['file-list']) {
  209. return {
  210. ...item['file-list'],
  211. type: 'file-list',
  212. }
  213. }
  214. if (item.file) {
  215. return {
  216. ...item.file,
  217. type: 'file',
  218. }
  219. }
  220. return {
  221. ...item['text-input'],
  222. type: 'text-input',
  223. }
  224. })
  225. }, [appParams])
  226. useEffect(() => {
  227. const conversationInputs: Record<string, any> = {}
  228. inputsForms.forEach((item: any) => {
  229. conversationInputs[item.variable] = item.default || null
  230. })
  231. handleNewConversationInputsChange(conversationInputs)
  232. }, [handleNewConversationInputsChange, inputsForms])
  233. const { data: newConversation } = useSWR(newConversationId ? [isInstalledApp, appId, newConversationId] : null, () => generationConversationName(isInstalledApp, appId, newConversationId), { revalidateOnFocus: false })
  234. const [originConversationList, setOriginConversationList] = useState<ConversationItem[]>([])
  235. useEffect(() => {
  236. if (appConversationData?.data && !appConversationDataLoading)
  237. setOriginConversationList(appConversationData?.data)
  238. }, [appConversationData, appConversationDataLoading])
  239. const conversationList = useMemo(() => {
  240. const data = originConversationList.slice()
  241. if (showNewConversationItemInList && data[0]?.id !== '') {
  242. data.unshift({
  243. id: '',
  244. name: t('share.chat.newChatDefaultName'),
  245. inputs: {},
  246. introduction: '',
  247. })
  248. }
  249. return data
  250. }, [originConversationList, showNewConversationItemInList, t])
  251. useEffect(() => {
  252. if (newConversation) {
  253. setOriginConversationList(produce((draft) => {
  254. const index = draft.findIndex(item => item.id === newConversation.id)
  255. if (index > -1)
  256. draft[index] = newConversation
  257. else
  258. draft.unshift(newConversation)
  259. }))
  260. }
  261. }, [newConversation])
  262. const currentConversationItem = useMemo(() => {
  263. let conversationItem = conversationList.find(item => item.id === currentConversationId)
  264. if (!conversationItem && pinnedConversationList.length)
  265. conversationItem = pinnedConversationList.find(item => item.id === currentConversationId)
  266. return conversationItem
  267. }, [conversationList, currentConversationId, pinnedConversationList])
  268. const currentConversationLatestInputs = useMemo(() => {
  269. if (!currentConversationId || !appChatListData?.data.length)
  270. return newConversationInputsRef.current || {}
  271. return appChatListData.data.slice().pop().inputs || {}
  272. }, [appChatListData, currentConversationId])
  273. const [currentConversationInputs, setCurrentConversationInputs] = useState<Record<string, any>>(currentConversationLatestInputs || {})
  274. useEffect(() => {
  275. if (currentConversationItem)
  276. setCurrentConversationInputs(currentConversationLatestInputs || {})
  277. }, [currentConversationItem, currentConversationLatestInputs])
  278. const { notify } = useToastContext()
  279. const checkInputsRequired = useCallback((silent?: boolean) => {
  280. let hasEmptyInput = ''
  281. let fileIsUploading = false
  282. const requiredVars = inputsForms.filter(({ required }) => required)
  283. if (requiredVars.length) {
  284. requiredVars.forEach(({ variable, label, type }) => {
  285. if (hasEmptyInput)
  286. return
  287. if (fileIsUploading)
  288. return
  289. if (!newConversationInputsRef.current[variable] && !silent)
  290. hasEmptyInput = label as string
  291. if ((type === InputVarType.singleFile || type === InputVarType.multiFiles) && newConversationInputsRef.current[variable] && !silent) {
  292. const files = newConversationInputsRef.current[variable]
  293. if (Array.isArray(files))
  294. fileIsUploading = files.find(item => item.transferMethod === TransferMethod.local_file && !item.uploadedId)
  295. else
  296. fileIsUploading = files.transferMethod === TransferMethod.local_file && !files.uploadedId
  297. }
  298. })
  299. }
  300. if (hasEmptyInput) {
  301. notify({ type: 'error', message: t('appDebug.errorMessage.valueOfVarRequired', { key: hasEmptyInput }) })
  302. return false
  303. }
  304. if (fileIsUploading) {
  305. notify({ type: 'info', message: t('appDebug.errorMessage.waitForFileUpload') })
  306. return
  307. }
  308. return true
  309. }, [inputsForms, notify, t])
  310. const handleStartChat = useCallback((callback: any) => {
  311. if (checkInputsRequired()) {
  312. setShowNewConversationItemInList(true)
  313. callback?.()
  314. }
  315. }, [setShowNewConversationItemInList, checkInputsRequired])
  316. const currentChatInstanceRef = useRef<{ handleStop: () => void }>({ handleStop: noop })
  317. const handleChangeConversation = useCallback((conversationId: string) => {
  318. currentChatInstanceRef.current.handleStop()
  319. setNewConversationId('')
  320. handleConversationIdInfoChange(conversationId)
  321. if (conversationId)
  322. setClearChatList(false)
  323. }, [handleConversationIdInfoChange, setClearChatList])
  324. const handleNewConversation = useCallback(() => {
  325. currentChatInstanceRef.current.handleStop()
  326. setShowNewConversationItemInList(true)
  327. handleChangeConversation('')
  328. handleNewConversationInputsChange({})
  329. setClearChatList(true)
  330. }, [handleChangeConversation, setShowNewConversationItemInList, handleNewConversationInputsChange, setClearChatList])
  331. const handleUpdateConversationList = useCallback(() => {
  332. mutateAppConversationData()
  333. mutateAppPinnedConversationData()
  334. }, [mutateAppConversationData, mutateAppPinnedConversationData])
  335. const handlePinConversation = useCallback(async (conversationId: string) => {
  336. await pinConversation(isInstalledApp, appId, conversationId)
  337. notify({ type: 'success', message: t('common.api.success') })
  338. handleUpdateConversationList()
  339. }, [isInstalledApp, appId, notify, t, handleUpdateConversationList])
  340. const handleUnpinConversation = useCallback(async (conversationId: string) => {
  341. await unpinConversation(isInstalledApp, appId, conversationId)
  342. notify({ type: 'success', message: t('common.api.success') })
  343. handleUpdateConversationList()
  344. }, [isInstalledApp, appId, notify, t, handleUpdateConversationList])
  345. const [conversationDeleting, setConversationDeleting] = useState(false)
  346. const handleDeleteConversation = useCallback(async (
  347. conversationId: string,
  348. {
  349. onSuccess,
  350. }: Callback,
  351. ) => {
  352. if (conversationDeleting)
  353. return
  354. try {
  355. setConversationDeleting(true)
  356. await delConversation(isInstalledApp, appId, conversationId)
  357. notify({ type: 'success', message: t('common.api.success') })
  358. onSuccess()
  359. }
  360. finally {
  361. setConversationDeleting(false)
  362. }
  363. if (conversationId === currentConversationId)
  364. handleNewConversation()
  365. handleUpdateConversationList()
  366. }, [isInstalledApp, appId, notify, t, handleUpdateConversationList, handleNewConversation, currentConversationId, conversationDeleting])
  367. const [conversationRenaming, setConversationRenaming] = useState(false)
  368. const handleRenameConversation = useCallback(async (
  369. conversationId: string,
  370. newName: string,
  371. {
  372. onSuccess,
  373. }: Callback,
  374. ) => {
  375. if (conversationRenaming)
  376. return
  377. if (!newName.trim()) {
  378. notify({
  379. type: 'error',
  380. message: t('common.chat.conversationNameCanNotEmpty'),
  381. })
  382. return
  383. }
  384. setConversationRenaming(true)
  385. try {
  386. await renameConversation(isInstalledApp, appId, conversationId, newName)
  387. notify({
  388. type: 'success',
  389. message: t('common.actionMsg.modifiedSuccessfully'),
  390. })
  391. setOriginConversationList(produce((draft) => {
  392. const index = originConversationList.findIndex(item => item.id === conversationId)
  393. const item = draft[index]
  394. draft[index] = {
  395. ...item,
  396. name: newName,
  397. }
  398. }))
  399. onSuccess()
  400. }
  401. finally {
  402. setConversationRenaming(false)
  403. }
  404. }, [isInstalledApp, appId, notify, t, conversationRenaming, originConversationList])
  405. const handleNewConversationCompleted = useCallback((newConversationId: string) => {
  406. setNewConversationId(newConversationId)
  407. handleConversationIdInfoChange(newConversationId)
  408. setShowNewConversationItemInList(false)
  409. mutateAppConversationData()
  410. }, [mutateAppConversationData, handleConversationIdInfoChange])
  411. const handleFeedback = useCallback(async (messageId: string, feedback: Feedback) => {
  412. await updateFeedback({ url: `/messages/${messageId}/feedbacks`, body: { rating: feedback.rating } }, isInstalledApp, appId)
  413. notify({ type: 'success', message: t('common.api.success') })
  414. }, [isInstalledApp, appId, t, notify])
  415. return {
  416. appInfoError,
  417. appInfoLoading: appInfoLoading || (systemFeatures.webapp_auth.enabled && (isGettingAccessMode || isCheckingPermission)),
  418. accessMode: systemFeatures.webapp_auth.enabled ? appAccessMode?.accessMode : AccessMode.PUBLIC,
  419. userCanAccess: systemFeatures.webapp_auth.enabled ? userCanAccessResult?.result : true,
  420. isInstalledApp,
  421. appId,
  422. currentConversationId,
  423. currentConversationItem,
  424. handleConversationIdInfoChange,
  425. appData,
  426. appParams: appParams || {} as ChatConfig,
  427. appMeta,
  428. appPinnedConversationData,
  429. appConversationData,
  430. appConversationDataLoading,
  431. appChatListData,
  432. appChatListDataLoading,
  433. appPrevChatTree,
  434. pinnedConversationList,
  435. conversationList,
  436. setShowNewConversationItemInList,
  437. newConversationInputs,
  438. newConversationInputsRef,
  439. handleNewConversationInputsChange,
  440. inputsForms,
  441. handleNewConversation,
  442. handleStartChat,
  443. handleChangeConversation,
  444. handlePinConversation,
  445. handleUnpinConversation,
  446. conversationDeleting,
  447. handleDeleteConversation,
  448. conversationRenaming,
  449. handleRenameConversation,
  450. handleNewConversationCompleted,
  451. newConversationId,
  452. chatShouldReloadKey,
  453. handleFeedback,
  454. currentChatInstanceRef,
  455. sidebarCollapseState,
  456. handleSidebarCollapse,
  457. clearChatList,
  458. setClearChatList,
  459. isResponding,
  460. setIsResponding,
  461. currentConversationInputs,
  462. setCurrentConversationInputs,
  463. }
  464. }