hooks.tsx 14 KB

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