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

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