hooks.tsx 16 KB

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