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.

hooks.tsx 17KB

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