hooks.tsx 14 KB

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