hooks.tsx 14 KB

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