hooks.tsx 15 KB

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