hooks.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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 {
  20. delConversation,
  21. fetchAppInfo,
  22. fetchAppMeta,
  23. fetchAppParams,
  24. fetchChatList,
  25. fetchConversations,
  26. generationConversationName,
  27. pinConversation,
  28. renameConversation,
  29. unpinConversation,
  30. updateFeedback,
  31. } from '@/service/share'
  32. import type { InstalledApp } from '@/models/explore'
  33. import type {
  34. AppData,
  35. ConversationItem,
  36. } from '@/models/share'
  37. import { addFileInfos, sortAgentSorts } from '@/app/components/tools/utils'
  38. import { useToastContext } from '@/app/components/base/toast'
  39. export const useChatWithHistory = (installedAppInfo?: InstalledApp) => {
  40. const isInstalledApp = useMemo(() => !!installedAppInfo, [installedAppInfo])
  41. const { data: appInfo, isLoading: appInfoLoading } = useSWR(installedAppInfo ? null : 'appInfo', fetchAppInfo)
  42. const appData = useMemo(() => {
  43. if (isInstalledApp) {
  44. const { id, app } = installedAppInfo!
  45. return {
  46. app_id: id,
  47. site: { title: app.name, icon: app.icon, icon_background: app.icon_background, prompt_public: false, copyright: '' },
  48. plan: 'basic',
  49. } as AppData
  50. }
  51. return appInfo
  52. }, [isInstalledApp, installedAppInfo, appInfo])
  53. const appId = useMemo(() => appData?.app_id, [appData])
  54. const [conversationIdInfo, setConversationIdInfo] = useLocalStorageState<Record<string, string>>(CONVERSATION_ID_INFO, {
  55. defaultValue: {},
  56. })
  57. const currentConversationId = useMemo(() => conversationIdInfo?.[appId || ''] || '', [appId, conversationIdInfo])
  58. const handleConversationIdInfoChange = useCallback((changeConversationId: string) => {
  59. if (appId) {
  60. setConversationIdInfo({
  61. ...conversationIdInfo,
  62. [appId || '']: changeConversationId,
  63. })
  64. }
  65. }, [appId, conversationIdInfo, setConversationIdInfo])
  66. const [showConfigPanelBeforeChat, setShowConfigPanelBeforeChat] = useState(true)
  67. const [newConversationId, setNewConversationId] = useState('')
  68. const chatShouldReloadKey = useMemo(() => {
  69. if (currentConversationId === newConversationId)
  70. return ''
  71. return currentConversationId
  72. }, [currentConversationId, newConversationId])
  73. const { data: appParams } = useSWR(['appParams', isInstalledApp, appId], () => fetchAppParams(isInstalledApp, appId))
  74. const { data: appMeta } = useSWR(['appMeta', isInstalledApp, appId], () => fetchAppMeta(isInstalledApp, appId))
  75. const { data: appPinnedConversationData, mutate: mutateAppPinnedConversationData } = useSWR(['appConversationData', isInstalledApp, appId, true], () => fetchConversations(isInstalledApp, appId, undefined, true, 100))
  76. const { data: appConversationData, isLoading: appConversationDataLoading, mutate: mutateAppConversationData } = useSWR(['appConversationData', isInstalledApp, appId, false], () => fetchConversations(isInstalledApp, appId, undefined, false, 100))
  77. const { data: appChatListData, isLoading: appChatListDataLoading } = useSWR(chatShouldReloadKey ? ['appChatList', chatShouldReloadKey, isInstalledApp, appId] : null, () => fetchChatList(chatShouldReloadKey, isInstalledApp, appId))
  78. const appPrevChatList = useMemo(() => {
  79. const data = appChatListData?.data || []
  80. const chatList: ChatItem[] = []
  81. if (currentConversationId && data.length) {
  82. data.forEach((item: any) => {
  83. chatList.push({
  84. id: `question-${item.id}`,
  85. content: item.query,
  86. isAnswer: false,
  87. message_files: item.message_files?.filter((file: any) => file.belongs_to === 'user') || [],
  88. })
  89. chatList.push({
  90. id: item.id,
  91. content: item.answer,
  92. agent_thoughts: addFileInfos(item.agent_thoughts ? sortAgentSorts(item.agent_thoughts) : item.agent_thoughts, item.message_files),
  93. feedback: item.feedback,
  94. isAnswer: true,
  95. citation: item.retriever_resources,
  96. message_files: item.message_files?.filter((file: any) => file.belongs_to === 'assistant') || [],
  97. })
  98. })
  99. }
  100. return chatList
  101. }, [appChatListData, currentConversationId])
  102. const [showNewConversationItemInList, setShowNewConversationItemInList] = useState(false)
  103. const pinnedConversationList = useMemo(() => {
  104. return appPinnedConversationData?.data || []
  105. }, [appPinnedConversationData])
  106. const { t } = useTranslation()
  107. const newConversationInputsRef = useRef<Record<string, any>>({})
  108. const [newConversationInputs, setNewConversationInputs] = useState<Record<string, any>>({})
  109. const handleNewConversationInputsChange = useCallback((newInputs: Record<string, any>) => {
  110. newConversationInputsRef.current = newInputs
  111. setNewConversationInputs(newInputs)
  112. }, [])
  113. const inputsForms = useMemo(() => {
  114. return (appParams?.user_input_form || []).filter((item: any) => item.paragraph || item.select || item['text-input']).map((item: any) => {
  115. if (item.paragraph) {
  116. return {
  117. ...item.paragraph,
  118. type: 'paragraph',
  119. }
  120. }
  121. if (item.select) {
  122. return {
  123. ...item.select,
  124. type: 'select',
  125. }
  126. }
  127. return {
  128. ...item['text-input'],
  129. type: 'text-input',
  130. }
  131. })
  132. }, [appParams])
  133. useEffect(() => {
  134. const conversationInputs: Record<string, any> = {}
  135. inputsForms.forEach((item: any) => {
  136. conversationInputs[item.variable] = item.default || ''
  137. })
  138. handleNewConversationInputsChange(conversationInputs)
  139. }, [handleNewConversationInputsChange, inputsForms])
  140. const { data: newConversation } = useSWR(newConversationId ? [isInstalledApp, appId, newConversationId] : null, () => generationConversationName(isInstalledApp, appId, newConversationId))
  141. const [originConversationList, setOriginConversationList] = useState<ConversationItem[]>([])
  142. useEffect(() => {
  143. if (appConversationData?.data && !appConversationDataLoading)
  144. setOriginConversationList(appConversationData?.data)
  145. }, [appConversationData, appConversationDataLoading])
  146. const conversationList = useMemo(() => {
  147. const data = originConversationList.slice()
  148. if (showNewConversationItemInList && data[0]?.id !== '') {
  149. data.unshift({
  150. id: '',
  151. name: t('share.chat.newChatDefaultName'),
  152. inputs: {},
  153. introduction: '',
  154. })
  155. }
  156. return data
  157. }, [originConversationList, showNewConversationItemInList, t])
  158. useEffect(() => {
  159. if (newConversation) {
  160. setOriginConversationList(produce((draft) => {
  161. const index = draft.findIndex(item => item.id === newConversation.id)
  162. if (index > -1)
  163. draft[index] = newConversation
  164. else
  165. draft.unshift(newConversation)
  166. }))
  167. }
  168. }, [newConversation])
  169. const currentConversationItem = useMemo(() => {
  170. let coversationItem = conversationList.find(item => item.id === currentConversationId)
  171. if (!coversationItem && pinnedConversationList.length)
  172. coversationItem = pinnedConversationList.find(item => item.id === currentConversationId)
  173. return coversationItem
  174. }, [conversationList, currentConversationId, pinnedConversationList])
  175. const { notify } = useToastContext()
  176. const checkInputsRequired = useCallback((silent?: boolean) => {
  177. if (inputsForms.length) {
  178. for (let i = 0; i < inputsForms.length; i += 1) {
  179. const item = inputsForms[i]
  180. if (item.required && !newConversationInputsRef.current[item.variable]) {
  181. if (!silent) {
  182. notify({
  183. type: 'error',
  184. message: t('appDebug.errorMessage.valueOfVarRequired', { key: item.variable }),
  185. })
  186. }
  187. return
  188. }
  189. }
  190. return true
  191. }
  192. return true
  193. }, [inputsForms, notify, t])
  194. const handleStartChat = useCallback(() => {
  195. if (checkInputsRequired()) {
  196. setShowConfigPanelBeforeChat(false)
  197. setShowNewConversationItemInList(true)
  198. }
  199. }, [setShowConfigPanelBeforeChat, setShowNewConversationItemInList, checkInputsRequired])
  200. const currentChatInstanceRef = useRef<{ handleStop: () => void }>({ handleStop: () => {} })
  201. const handleChangeConversation = useCallback((conversationId: string) => {
  202. currentChatInstanceRef.current.handleStop()
  203. setNewConversationId('')
  204. handleConversationIdInfoChange(conversationId)
  205. if (conversationId === '' && !checkInputsRequired(true))
  206. setShowConfigPanelBeforeChat(true)
  207. else
  208. setShowConfigPanelBeforeChat(false)
  209. }, [handleConversationIdInfoChange, setShowConfigPanelBeforeChat, checkInputsRequired])
  210. const handleNewConversation = useCallback(() => {
  211. currentChatInstanceRef.current.handleStop()
  212. setNewConversationId('')
  213. if (showNewConversationItemInList) {
  214. handleChangeConversation('')
  215. }
  216. else if (currentConversationId) {
  217. handleConversationIdInfoChange('')
  218. setShowConfigPanelBeforeChat(true)
  219. setShowNewConversationItemInList(true)
  220. handleNewConversationInputsChange({})
  221. }
  222. }, [handleChangeConversation, currentConversationId, handleConversationIdInfoChange, setShowConfigPanelBeforeChat, setShowNewConversationItemInList, showNewConversationItemInList, handleNewConversationInputsChange])
  223. const handleUpdateConversationList = useCallback(() => {
  224. mutateAppConversationData()
  225. mutateAppPinnedConversationData()
  226. }, [mutateAppConversationData, mutateAppPinnedConversationData])
  227. const handlePinConversation = useCallback(async (conversationId: string) => {
  228. await pinConversation(isInstalledApp, appId, conversationId)
  229. notify({ type: 'success', message: t('common.api.success') })
  230. handleUpdateConversationList()
  231. }, [isInstalledApp, appId, notify, t, handleUpdateConversationList])
  232. const handleUnpinConversation = useCallback(async (conversationId: string) => {
  233. await unpinConversation(isInstalledApp, appId, conversationId)
  234. notify({ type: 'success', message: t('common.api.success') })
  235. handleUpdateConversationList()
  236. }, [isInstalledApp, appId, notify, t, handleUpdateConversationList])
  237. const [conversationDeleting, setConversationDeleting] = useState(false)
  238. const handleDeleteConversation = useCallback(async (
  239. conversationId: string,
  240. {
  241. onSuccess,
  242. }: Callback,
  243. ) => {
  244. if (conversationDeleting)
  245. return
  246. try {
  247. setConversationDeleting(true)
  248. await delConversation(isInstalledApp, appId, conversationId)
  249. notify({ type: 'success', message: t('common.api.success') })
  250. onSuccess()
  251. }
  252. finally {
  253. setConversationDeleting(false)
  254. }
  255. if (conversationId === currentConversationId)
  256. handleNewConversation()
  257. handleUpdateConversationList()
  258. }, [isInstalledApp, appId, notify, t, handleUpdateConversationList, handleNewConversation, currentConversationId, conversationDeleting])
  259. const [conversationRenaming, setConversationRenaming] = useState(false)
  260. const handleRenameConversation = useCallback(async (
  261. conversationId: string,
  262. newName: string,
  263. {
  264. onSuccess,
  265. }: Callback,
  266. ) => {
  267. if (conversationRenaming)
  268. return
  269. if (!newName.trim()) {
  270. notify({
  271. type: 'error',
  272. message: t('common.chat.conversationNameCanNotEmpty'),
  273. })
  274. return
  275. }
  276. setConversationRenaming(true)
  277. try {
  278. await renameConversation(isInstalledApp, appId, conversationId, newName)
  279. notify({
  280. type: 'success',
  281. message: t('common.actionMsg.modifiedSuccessfully'),
  282. })
  283. setOriginConversationList(produce((draft) => {
  284. const index = originConversationList.findIndex(item => item.id === conversationId)
  285. const item = draft[index]
  286. draft[index] = {
  287. ...item,
  288. name: newName,
  289. }
  290. }))
  291. onSuccess()
  292. }
  293. finally {
  294. setConversationRenaming(false)
  295. }
  296. }, [isInstalledApp, appId, notify, t, conversationRenaming, originConversationList])
  297. const handleNewConversationCompleted = useCallback((newConversationId: string) => {
  298. setNewConversationId(newConversationId)
  299. handleConversationIdInfoChange(newConversationId)
  300. setShowNewConversationItemInList(false)
  301. mutateAppConversationData()
  302. }, [mutateAppConversationData, handleConversationIdInfoChange])
  303. const handleFeedback = useCallback(async (messageId: string, feedback: Feedback) => {
  304. await updateFeedback({ url: `/messages/${messageId}/feedbacks`, body: { rating: feedback.rating } }, isInstalledApp, appId)
  305. notify({ type: 'success', message: t('common.api.success') })
  306. }, [isInstalledApp, appId, t, notify])
  307. return {
  308. appInfoLoading,
  309. isInstalledApp,
  310. appId,
  311. currentConversationId,
  312. currentConversationItem,
  313. handleConversationIdInfoChange,
  314. appData,
  315. appParams: appParams || {} as ChatConfig,
  316. appMeta,
  317. appPinnedConversationData,
  318. appConversationData,
  319. appConversationDataLoading,
  320. appChatListData,
  321. appChatListDataLoading,
  322. appPrevChatList,
  323. pinnedConversationList,
  324. conversationList,
  325. showConfigPanelBeforeChat,
  326. setShowConfigPanelBeforeChat,
  327. setShowNewConversationItemInList,
  328. newConversationInputs,
  329. handleNewConversationInputsChange,
  330. inputsForms,
  331. handleNewConversation,
  332. handleStartChat,
  333. handleChangeConversation,
  334. handlePinConversation,
  335. handleUnpinConversation,
  336. conversationDeleting,
  337. handleDeleteConversation,
  338. conversationRenaming,
  339. handleRenameConversation,
  340. handleNewConversationCompleted,
  341. newConversationId,
  342. chatShouldReloadKey,
  343. handleFeedback,
  344. currentChatInstanceRef,
  345. }
  346. }