hooks.tsx 14 KB

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