hooks.tsx 14 KB

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