hooks.tsx 14 KB

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