hooks.tsx 16 KB

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